xml 如何选择不同级别的多个节点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11040469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 13:32:18  来源:igfitidea点击:

How to select multiple nodes in different levels?

xmlxpathxml-parsing

提问by Alejandro García Iglesias

Having this (simplified) XML:

拥有这个(简化的)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:

如何选择每个地标的名称和坐标?现在我可以使用以下 XPath 表达式选择他们的名字:

//Document//Placemark//name

How can I select both without any other data?

如何在没有任何其他数据的情况下选择两者?

回答by toniedzwiedz

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

您可以在 XPath 表达式中使用联合。只需使用运算符:|

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

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

如果不需要,请不要使用//后代轴)。使用//,这也将工作://name | //coordinates。指定确切路径在性能方面会更好。

回答by Dimitre Novatchev

Use:

使用

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

This specifies the unionof the results of two separate XPath expressions -- the standard XPath union operator |is used. Selected are all nameelements that are children of a Placemarkelement that is a grandchild of the top element of the XML document, plusall coordinateselements that are grand-children of a Placemarkelement that is a grandchild of the top element of the XML document.

这指定了两个单独的 XPath 表达式的结果的联合——使用标准的 XPath 联合运算符|。选择都name认为是儿童的元素Placemark是XML文档的顶级元素的孙子元素,再加上所有的coordinates是一个宏大的,子元素Placemark是XML文档的顶级元素的孙元素。

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 nameelement is directly followed by its corresponding coordinateselement.

所选元素按文档顺序出现(尽管没有规范的 W3C 文档指定顺序),这意味着在评估结果(通常是 XmlNodeList 类型)中,任何name元素都直接跟在其对应的coordinates元素之后。

回答by luis long

Resolved: //Placemark/*[self::name or descendant::coordinates]

已解决://Placemark/*[self::name 或descendant::coordinates]