Tags

links:
tester – http://www.xpathtester.com/test
funcs – http://www.w3schools.com/xpath/xpath_functions.asp
axes – http://www.w3schools.com/xpath/xpath_axes.asp
tutorial – http://www.zvon.org/xxl/XPathTutorial/General/examples.html
namespace – http://blog.davber.com/2006/09/17/xpath-with-namespaces-in-java



Default namespace needs ":"
----------------------------
If namespace aware, must be specified,
i.e.    //ns1:tag

Tricky thing is "default" namespace, we still need ":" before tag.
i.e.    //:tag (beware, not xpath std)

HOWEVER, THIS IS NOT STANDAND ( getting trickier? ). Some of the
Xpath processors would take it (e.g. w3c dom in Java, Xalan), 
but others like Saxon would fail saying "unexpected colon" which
is right because this is indeed not following valid xpath syntax.

The workaround in your xpath exp is to use a prefix but set it
to an empty string, i.e. "".  (what else can we do?)



Namespace Aware setups
-----------------------
- NamespaceContext interface
- setNamespaceAware(true) in DocumentBuilderFactory
- use ":" in xpath expressions


Xpath idx is 1 base
---------------------
e.g. //tag[1]
starting from idx 1
Notes: heard some IE is wrong going by 0 base. 


Attribute node
---------------
For an attribute, it seems as a child node. 
e.g.  get "id" from  <tag id="123"/>

  //tag/@id - select attribute id, so "/" is needed 


Xpath needs () ?  maybe for "[]" precedence?
---------------------------------------------
e.g. //tag[@attr="123"][1]
This is not working for some reason in my java program.
Must add the "(" ")" to work, 
i.e. 
(//tag[@attr="123"])[1]


Node types
----------
query results have types; attr, text, node, etc; not just nodes

  /aaa - root element aaa
  aaa - all element aaa
  //aaa - all aaa in any level
  /*/aaa - all aaa 1st level down
  /*/aaa[1] - 1st level, 1st occurrence of aaa
  /*/aaa[@id] - 1st level all aaa having attr "id" 
  /*/aaa[not(@*)] - 1st level all aaa having no attr
  //@id - all attrs "id" and values, only attrs, no node? seems just values
  //*[@id="321"] - all nodes with attr id equal to 321
  //*[count(aaa)=3] - all nodes having 3 aaa children
  //*[string-length(name())=3] - all nodes with name length equal to 3
  count(//dev[@id='1234']) - number of nodes returned

	public NodeList getNodesXp(Document xdoc, String xpexp)
         {		
		NodeList nl = null;
		try {
			XPathFactory factory = XPathFactory.newInstance();
		         XPath xpath = factory.newXPath();
		         xpath.setNamespaceContext(nsctx);
			try {
				XPathExpression expr = xpath.compile(xpexp);
				Object result=expr.evaluate(xdoc, XPathConstants.NODESET);
				nl = (NodeList)result;		
			} catch (XPathExpressionException e) {
				lgr.error("no node found: "+xpexp);
			}						

		} catch (Exception e) {
			lgr.error("Other err:"+e.getMessage(), e);
		}		
		return nl;
	}

Advertisements