简体   繁体   中英

why does Element::getElementsByTagNameNS fail?

Given the XML instance document:

<foo:A xmlns:foo="http://foo" >
    <foo:ListRecords>
        <foo:record>
        </foo:record>
    </foo:ListRecords>
</foo:A>

The following code:

import java.io.File;

import javax.xml.parsers.*;
import org.w3c.dom.*;


public class FooMain {

    public static void main(String args[]) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new File("record.xml"));
        Element rootElement = document.getDocumentElement();
        NodeList records1 = rootElement.getElementsByTagNameNS("*", "record");
        NodeList records2 = rootElement.getElementsByTagNameNS("http://foo", "record");
        NodeList records3 = rootElement.getElementsByTagName("foo:record");
        System.out.printf("%d records1 found.\n", records1.getLength());
        System.out.printf("%d records2 found.\n", records2.getLength());
        System.out.printf("%d records3 found.\n", records3.getLength());
    }
}

prints:

0 records1 found.
0 records2 found.
1 records3 found.

You need a namespace-aware parser. By default , JDK parsers are not namespace aware.

Change your code to look like this:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

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