【问题标题】:How can I retrieve the child node using xpath Java如何使用 xpath Java 检索子节点
【发布时间】:2018-07-13 08:26:58
【问题描述】:

我有一个如下所示的 xml 文件

 <Placemark>
    <name>west am</name>
    <styleUrl>#msn_ylw-pushpin0</styleUrl>
    <Polygon>
        <tessellate>1</tessellate>
        <outerBoundaryIs>
            <LinearRing>
                <coordinates>
                    -59.6227959506966,55.37494940456102,0            
                </coordinates>
            </LinearRing>
        </outerBoundaryIs>
    </Polygon>
</Placemark>
<Placemark>
    <name>east am</name>
    <styleUrl>#msn_ylw-pushpin10</styleUrl>
    <Polygon>
        <tessellate>1</tessellate>
        <outerBoundaryIs>
            <LinearRing>
                <coordinates>
                    -118.5321721528021,34.65735513563493,0                   
                </coordinates>
            </LinearRing>
        </outerBoundaryIs>`
    </Polygon>
</Placemark>

如何使用 xpath 检索标签值为“east am”的标签。

感谢您的支持。

【问题讨论】:

标签: java xml xpath


【解决方案1】:

虽然您需要代码来读取和解析来自某些源和类的 xml 以管理和操作 xml 信息集,但答案归结为以下 XPath 表达式:

//Placemark/name[./text()='east am']

这个表达式选择 ...

  • name 元素,正在...
  • ...Placemark 元素的子元素...
  • ...文档中的任何位置,...
  • ...name 元素的文本内容为east am

替代方案

//Placemark/name[string(.)='east am']

有关string(.)./text() 之间区别的完整讨论,请参阅this SO answer

基本上,一方面,如果 xml 节点的文本内容由多个文本节点表示,./text() 会失败。 AFAIK 这个决定是由解析器做出的,你无法指导这个选择。

另一方面,如果目标name 节点属于复杂类型,即。可能有带有自己文本内容的子元素,您需要指定目标元素本身及其后代的所有文本片段的串联。

代码

此代码是一个独立示例,用于从作为示例给出的 xml 文件中收集由给定 xpath 表达式引用的节点的表示。

此代码源自this SO answer,所有归功于其作者,与我无关。

请注意,您的 xml 摘录不是有效的独立 xml 文件,因为它缺少单个根元素。如果文件还没有合成根,则将其添加到文件中(xpath 表达式可以使用任何一种方式)。

文件名是xpath.javatest.51320827.xml。用 java 1.8.0_45 测试;

//  https://stackoverflow.com/questions/51320827/how-can-i-retrieve-the-child-node-using-xpath-java
//
//  code taken from:    https://stackoverflow.com/a/47280397
//
//
import java.lang.*;
import java.io.*;
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class xpath {
    public static void main(String[] args) {
        String xpathExpression = "//Placemark/name[./text()='east am']";

        // Read file
        Document doc = null;
        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = factory.newDocumentBuilder();
            File file = new File( "test.51320827.xml" );
            FileInputStream stream = new FileInputStream( file );
            doc = builder.parse( stream );
        } catch (SAXException | IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        // get from XPath
        try {
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();

            XPathExpression compile = xpath.compile(xpathExpression);
            NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);

            displayNodeList(nodeList);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        System.out.println("\n===== ***** =====");
    }

    static void displayNodeList( NodeList nodeList ) {
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            String NodeName = node.getNodeName();

            NodeList childNodes = node.getChildNodes();
            if ( childNodes.getLength() > 1 ) {
                for (int j = 0; j < childNodes.getLength(); j++) {

                    Node child = childNodes.item(j);
                    short nodeType = child.getNodeType();
                    if ( nodeType == 1 ) {
                        System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
                    }
                }
            } else {
                System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
            }

        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多