【问题标题】:XPath to get all sub-nodes & valuesXPath 获取所有子节点和值
【发布时间】:2017-08-17 20:53:59
【问题描述】:

我正在尝试从以下 XML 源中获取所有活动及其子节点。

<process>
  <name>processName</name>
  <input>JSON</input>
  <input>productName</input>
  <output>JSON</output>
  <activity>
    <name>createDomain</name>
    <type>bean</type>
    <input>domainName</input>
    <output>JSON</output>
  </activity>
  <mapActivity>
    <map></map>
  </mapActivity>
  <activity>
    <name>preFill</name>
    <type>REST</type>
    <input>JSON</input>
    <output>JSON</output>
  </activity>
</process>

因此结果将返回createDomain, bean, domainName, JSONpreFill, REST, JSON, JSON。但我不确定如何去做。

我目前有这个代码。

    public static void displayActivities(Document myDoc) throws Exception {
    XPathExpression exp = xp.compile("process/activity/*");
    NodeList myList = (NodeList) exp.evaluate(myDoc, XPathConstants.NODESET);
    for (int i = 0; i < myList.getLength(); i++) {
        Node tempNode = myList.item(i);
        System.out.println("Value: " + tempNode.getNodeValue());
        if (tempNode.hasChildNodes()) {
            for (int x = 0; x < tempNode.getChildNodes().getLength(); x++) {
                System.out.println("Sub-value: " + myDoc.getChildNodes().item(x).getNodeName());
            }
        }
    }
    System.out.println("------------------------------");
}

这将返回以下内容:

Value: null
Sub-value: process

【问题讨论】:

    标签: java json xml xpath nodes


    【解决方案1】:

    在 Java 中使用 DOM 时,一切都是节点。元素是节点,文本是节点等等。您的 XPath 将返回完整的 XML 元素:

    • 创建域
    • 类型>
    • JSON输入>
    • JSON输出>

    意味着 tempNode 实际上是 Element 类型,而不是文本。您将在子节点中找到文本。根据Node Javadoc,当调用 getNodeValue() 时,元素将返回 null。

    【讨论】:

      猜你喜欢
      • 2012-09-17
      • 2023-03-27
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2023-03-26
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多