简体   繁体   中英

Java w3c dom getElementsByTagName does not return any node

I have this code and only list3 has length different than zero. Is it possible to get nodelist by local tag name, without namespace prefix, like 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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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