开发者

getElementsByTagName doesn't work

开发者 https://www.devze.com 2023-04-04 23:09 出处:网络
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&g

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)));                    
NodeL开发者_开发知识库ist 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?


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号