简体   繁体   English

Java w3c dom getElementsByTagName 不返回任何节点

[英]Java w3c dom getElementsByTagName does not return any node

I have this code and only list3 has length different than zero.我有这段代码,只有 list3 的长度不为零。 Is it possible to get nodelist by local tag name, without namespace prefix, like list4?是否可以通过本地标签名称获取节点列表,而无需命名空间前缀,如 list4?

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(entry.toFile());
        
        NodeList list = doc.getElementsByTagNameNS("http://wtest2", "entry");
        NodeList list2 = doc.getElementsByTagNameNS("x1", "entry");
        NodeList list3 = doc.getElementsByTagName("x1:entry");
        NodeList list4 = doc.getElementsByTagName("entry");
 

And below is the XML which I am processing:下面是我正在处理的 XML:

<?xml version="1.0" encoding="UTF-8"?>
<x1:myroot
        xmlns:bob="urn:test"
        xmlns:x1="http://wtest2"
        version="1.0">
    <bob:header/>
    <x1:entry>
        <x1:data>
            <x1:person>
                <bob:name>test</bob:name>
            </x1:person>
        </x1:data>
    </x1:entry>
    <x1:entry>
        <x1:data>
            <x1:person>
                <bob:name>test2</bob:name>
            </x1:person>
        </x1:data>
    </x1:entry>

</x1:myroot>

Since you create factory/builder that is not namespace aware, the tag name is literally "x1:entry", without any namespace.由于您创建的工厂/构建器不支持名称空间,因此标签名称实际上是“x1:entry”,没有任何名称空间。

You need to call你需要打电话

dbf.setNamespaceAware(true);

Then然后

NodeList list = doc.getElementsByTagNameNS("http://wtest2", "entry");

should work.应该管用。 You can also use "*" as the value for the namespaceURI parameter.您还可以使用“*”作为 namespaceURI 参数的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM