如何基于XPath表达式返回XML请求的子部分

时间:2018-07-07 14:22:59

标签: java xml xpath

我已经编写了代码,使我能够基于给定的XPath进入xml请求的一个子节,但是,返回的只是标签之间的值,而不是标签。

我希望基于给定的xpath返回值和元素。

例如,在此xml中:

?xml version="1.0"?>
<company>
  <staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>
  <staff2>
    <name>mary</name>
    <phone>4655556433</phone>
    <email>gmail2</email>
    <area>area2</area>
    <city>city2</city>
  </staff2>
  <staff3>
    <name>furvi</name>
    <phone>4655433</phone>
    <email>gmail3</email>
    <area>area3</area>
    <city>city3</city>
  </staff3>
</company>

我的XPath仅返回第一个staff元素的值,即

John
465456433
gmail1
area1
city1

它不返回与其关联的标签,即它应该返回以下内容:

<staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>

这是我的代码:

      InputSource inputSource = new InputSource(new StringReader(xmlString));
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            String RecordCategory;

        Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputSource);

        // Create XPathFactory object
        XPathFactory xpathFactory = XPathFactory.newInstance();

        // Create XPath object
        XPath xpath = xpathFactory.newXPath();

        System.out.println("TESTING XPATH");

        xpath.setNamespaceContext(new NamespaceContext() {
            @Override
            public String getNamespaceURI(String prefix) {
...
               });
    XPathExpression expr = xpath.compile("//staff1[1]");




        Staff1 = (String) expr.evaluate(doc,XPathConstants.STRING);
        System.out.println("staff1: " + staff1);

任何人对我可以解决此问题有任何想法吗?

1 个答案:

答案 0 :(得分:0)

您对XPathExpression.evaluation()的Java调用返回了XPath表达式选择的节点的 字符串值 。如果您想返回由XPath表达式选择的 节点 ,请更改

Staff1 = (String) expr.evaluate(doc, XPathConstants.STRING);

Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);

有关如何漂亮打印node的信息,请参见this answer