【问题标题】:Accessing the length of child nodes returns twice the original count访问子节点的长度会返回原始计数的两倍
【发布时间】:2015-03-17 01:50:39
【问题描述】:

我一直在尝试通过获取item 节点的长度来迭代子节点。但是,它显示的是原始长度的两倍。

这是我一直在使用的 XML 代码,

    <item>
        <title>Title 1</title>
        <link>http://www.example.com</link>
        <comments>http://www.example.com/#comments</comments>
        <pubDate>Mon, 19 Jan 2015 04:05:39 +0000</pubDate>
        <dc:creator><![CDATA[Exampple]]></dc:creator>
        <category><![CDATA[Hot News]]></category>
        <guid isPermaLink="false">http://www.example.com/?p=72278</guid>
        <description><![CDATA[<p>Some Description</p>]]></description>
        <content:encoded><![CDATA[<p>Some description content.</p>]]></content:encoded>
        <wfw:commentRss>http://www.example.com/feed/</wfw:commentRss>
    </item>

Java 代码:

NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
Log.d("check", "Item i count = " + length); //shows 10
for (int i = 0; i < length; i++) {
    Node currentNode = nl.item(i); // Get the first item
    String nodetestName = currentNode.getNodeName();
    NodeList nchild = currentNode.getChildNodes(); // Get the child nodes of first item
    int clength = nchild.getLength(); // Get the length of child nodes of first item (Shows 21 but original length is 10)

我该怎么办?

【问题讨论】:

标签: java android xml dom


【解决方案1】:

尝试忽略空格,它对我有用。

docBuilderFactory.setIgnoringElementContentWhitespace(true);

【讨论】:

    【解决方案2】:

    您忘记了子元素之间的空白文本节点也是节点,并且包含在 getChildNodes() 的结果中。不记得如何最好地解决这个问题:我避免像瘟疫一样使用 DOM。

    【讨论】:

    • 我应该如何处理空白文本节点或至少在处理数据和速度方面非常有效的 DOM 的任何其他最佳替代方案?顺便说一句,感谢您的指出。
    • 我忘记了 DOM 是否可以选择构建没有空白文本节点的树。如果我使用 Java 访问 XML 的树表示,我首选的模型是 XOM 或 JDOM2。但只要有可能,我都会尝试使用专为这项工作设计的语言进行所有 XML 操作:XSLT 和 XQuery。即使在 Java 中,我也会通过调用 XPath 来完成几乎所有事情。
    【解决方案3】:

    可能您在 NodeList 中添加项目而不清空列表。

    【讨论】:

    • 如何清空列表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多