Will
Will

Reputation: 2978

XPath NodeList order (Java)

I have the following XML structure.

<?xml version="1.0" encoding="UTF-8"?>
<root> 
  <header> 
    <row> 
      <column n="name" />
      <column n="age" />
      <column n="email" />
    </row> 
  </header>  
  <body> 
    <row> 
      <column>Foo</column>  
      <column>99</column>  
      <column>[email protected]</column> 
    </row>  
  </body> 
</root>

I'm using the following XPath expression to get the header columns and likewise to get the body columns.

PathExpression headerExpr = xPath.compile("/root/header/row/column/@n");
NodeList headerColumns = (NodeList) headerExpr.evaluate(document, XPathConstants.NODESET);
PathExpression bodyExpr = xPath.compile("/root/body/row/column");
NodeList bodyColumns = (NodeList) bodyExpr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < headerColumns.getLength(); i++) {
                System.out.println((Attr) headerColumns .item(i)).getValue() + ": " + bodyColumns.item(i).getTextContent());
        }

Can I assume that XPath will always return the header and body columns in the same order so that they will always match? Or can I even assume that the columns are always returned in document order?

Upvotes: 6

Views: 2950

Answers (1)

JWiley
JWiley

Reputation: 3219

The document order is always preserved when using XPath, here's something official for your reference: http://msdn.microsoft.com/en-us/library/ms256090.aspx

Upvotes: 5

Related Questions