XPath NodeList order (Java)
Asked Answered
A

1

6

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?

Abacus answered 7/2, 2013 at 14:34 Comment(5)
Have you tested it? This sounds like a fairly obvious question, so there's probably documentation on it.Clabber
XPath traverses top down, so if you're asking whether or not you'll get back "name, age, email" instead of some random ordering you are correct.Swanhilda
I've tested it and it works, however I coulnd't find any documentation within 15min stating that XPath will return children in document order. So if you can point me to the spec that will be perfectAbacus
If you implementation of XPath behaves consistently then you can probably use the node order.Rhinarium
If I understand this specification correctly, the document order will dictate the order of elements. I am however not sure that that spec is current.Clabber
S
5

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

Swanhilda answered 7/2, 2013 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.