Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementsByTagName doesn't work

I have next simple part of code:

String test = "<?xml version="1.0" encoding="UTF-8"?><TT_NET_Result><GUID>9145b1d3-4aa3-4797-b65f-9f5e00be1a30</GUID></TT_NET_Result>"

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(test)));                    
NodeList nl = doc.getDocumentElement().getElementsByTagName("TT_NET_Result");

The problem is that I don't get any result - nodelist variable "nl" is empty. What could be wrong?

like image 997
torosg Avatar asked Feb 23 '23 23:02

torosg


2 Answers

You're asking for elements under the document element, but TT_NET_Result is the document element. If you just call

NodeList nl = doc.getElementsByTagName("TT_NET_Result");

then I suspect you'll get the result you want.

like image 140
Jon Skeet Avatar answered Feb 25 '23 15:02

Jon Skeet


Here's another response to this old question. I hit a similar issue in my code today and I actually read/write XML all the time. For some reason I overlooked one major fact. If you want to use

NodeList elements = doc.getElementsByTagNameNS(namespace,elementName);

You need to parse your document with a factory that is namespace-aware.

private static DocumentBuilderFactory getFactory() {
    if (factory == null){
        factory = DocumentBuilderFactory
                .newInstance();
        factory.setNamespaceAware(true);
    }
    return factory;
}
like image 20
David Brossard Avatar answered Feb 25 '23 15:02

David Brossard