【问题标题】:Unable to get Name attribute of Childnode无法获取子节点的名称属性
【发布时间】:2013-03-15 18:41:14
【问题描述】:

我有一个如下所示的 XML 文件:

<exist:result xmlns:exist="http://exist.sourceforge.net/NS/exist">
<exist:collection name="/db/RCM" created="2013-03-24T09:37:34.957+05:30" owner="admin" group="dba" permissions="rwxrwxrwx">
<exist:resource name="demo2.xml" created="2013-03-24T09:44:13.696+05:30" last-modified="2013-03-24T09:44:13.696+05:30" owner="guest" group="guest" permissions="rw-r--r--"/>
<exist:resource name="demo3.xml" created="2013-03-24T09:45:47.592+05:30" last-modified="2013-03-24T09:45:47.592+05:30" owner="guest" group="guest" permissions="rw-r--r--"/>
<exist:resource name="rcmdemo.xml" created="2013-03-25T11:36:45.659+05:30" last-modified="2013-03-25T11:36:45.659+05:30" owner="guest" group="guest" permissions="rw-r--r--"/>
<exist:resource name="rcmdemo2.xml" created="2013-03-25T11:47:03.564+05:30" last-modified="2013-03-25T11:47:03.564+05:30" owner="guest" group="guest" permissions="rw-r--r--"/>
</exist:collection>
</exist:result>

我想获取 XML 文件的名称,所以输出如下所示:

demo2.xml
demo3.xml
rcmdemo.xml
rcmdemo2.xml

我写了以下代码:

NodeList nodeList = doc.getElementsByTagName("exist:resource");
for (int i = 0; i < nodeList.getLength(); i++) {
    Node n = nodeList.item(i);
    Node actualNode = n.getFirstChild();
    if (actualNode != null) {
        System.out.println(actualNode.getNodeValue());
    }
}

但它没有返回我想要的输出,我哪里出错了?

【问题讨论】:

  • 我认为 name 不是子节点,请检查给定节点的属性。

标签: java dom xml-parsing


【解决方案1】:

在此示例中,名称是节点的属性,而不是节点的名称。请查看以下问题以获取有关节点属性的信息,特别是第二个答案是我认为您正在寻找的内容。

get the the attributes from an XML File using Java

【讨论】:

    【解决方案2】:

    您必须从给定节点获取属性,因为您的nameexist:resource 的属性。

    NodeList nodeList = doc.getElementsByTagName("exist:resource");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node n = nodeList.item(i);
                Node actualNode = n.getFirstChild();
                if (actualNode != null) {
                    // Will return node value
                    System.out.println(actualNode.getNodeValue());
                    // Will return the attribute value
                    System.out.println(current.getAttributeValue("name")); 
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      • 2012-02-29
      • 1970-01-01
      • 2010-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多