How to select multiple nodes in different levels?

30,665

Solution 1

You can use a union in your XPath expression. Just use the operator: |

//Document/Placemark/name | //Document/Placemark/Polygon/coordinates

Don't use the // (descendant axis) if you don't need to. Using //, this would also work: //name | //coordinates. It's better performance-wise to specify the exact path.

Solution 2

Use:

/*/*/Placemark/name | /*/*/Placemark/*/coordinates

This specifies the union of the results of two separate XPath expressions -- the standard XPath union operator | is used. Selected are all name elements that are children of a Placemark element that is a grandchild of the top element of the XML document, plus all coordinates elements that are grand-children of a Placemark element that is a grandchild of the top element of the XML document.

The selected elements come in document order (although no normative W3C document specifies the order), which means that in the result of the evaluation (usually of type XmlNodeList) any name element is directly followed by its corresponding coordinates element.

Share:
30,665
Alejandro García Iglesias
Author by

Alejandro García Iglesias

Front-end Developer, UI design lover.

Updated on July 09, 2022

Comments

  • Alejandro García Iglesias
    Alejandro García Iglesias almost 2 years

    Having this (simplified) XML:

    <?xml version="1.0" encoding="UTF-8"?>
    <kml>
    <Document>
            <Placemark>
                <name>Poly 1</name>
                <Polygon>
                            <coordinates>
                                -58.40844625779582,-34.60295278618136,0
                            </coordinates>
                </Polygon>
            </Placemark>
            <Placemark>
                <name>Poly 2</name>
                <Polygon>
                            <coordinates>
                                -58.40414334150432,-34.59992445476809,0
                            </coordinates>
                </Polygon>
            </Placemark>
    </Document>
    </kml>
    

    How can I select the name and coordinates of each Placemark? Right now I can select their name with the following XPath expression:

    //Document//Placemark//name
    

    How can I select both without any other data?

  • U. Windl
    U. Windl over 2 years
    Is there a simplification that avoids repeating //Document/Placemark/?