开发者社区> 问答> 正文

xml,怎么通过dom用java读取出item的值:报错

对于如下的xml,怎么通过dom用java读取出item的值啊?

<resources xmlns:xliff="urn:oasis:names����xliff:document:1.2"> 
    <!-- The time zone picker screen has two levels.  The first level allows the user to choose a region. -->
    <string-array name="timezone_filters"> 
    <!-- The next level of the time zoner picker should show time zones from the Americas. -->
        <item>America</item> 
    <!-- The next level of the time zoner picker should show time zones from Europe. -->
        <item>Europe</item> 
    <!-- The next level of the time zoner picker should show time zones from Africa. -->
        <item>Africa</item> 
    <!-- The next level of the time zoner picker should show time zones from Asia. -->
        <item>Asia</item> 
    <!-- The next level of the time zoner picker should show time zones from Australia. -->
        <item>Australia</item> 
    <!-- The next level of the time zoner picker should show time zones from Pacific. -->
        <item>Pacific</item> 
    <!-- The next level of the time zoner picker should show time zones from ALL regions. -->
        <item>All</item> 
    </string-array> 
</resources> 
我是这样写的:
NodeList nodeList = doc.getElementsByTagName("string-array");
NodeList itemList = nodeList.item(0).getChildNodes();
int itemSize = itemList.getLength();

for (int i = 0; i < itemSize ; i++)
{
    Node item = itemList.item(i);
    System.out.println("item value = " + item.getTextContent());
}
这样写打印出了好多空值、换行符。并且itemSize = 29 。
明显错了。但是该怎么写呢?

展开
收起
kun坤 2020-06-09 12:16:15 469 0
1 条回答
写回答
取消 提交回答
  • nodeList.item(0).getChildNodes(); 问题出在这句,getChildNodes()不知道可不可以加个参数来指定item。 我解析xml一般用jsoup,这个比dom4j好用多了。######恩。是要通过参数来指定item的。直接用Node好像不行。 我这里直接吧Node强制转化为Element了。这样就可以了。 Jsoup是个好东西。只是我还要写入到xml里面。 感谢回答!!######真正的原因是这里:normalize(); 在document.parse()之后,调用document.normalize()就可以除掉空格换行符了

    2020-06-09 12:16:22
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载