无法使用DOM解析器读取具有名称空间前缀的xml [英] Unable to read xml with namespace prefix using DOM parser

查看:195
本文介绍了无法使用DOM解析器读取具有名称空间前缀的xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是输入XML:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <ns2:SendResponse xmlns:ns2="http://mycompany.com/schema/">
         <ns2:SendResult>
            <ns2:Token>A00179-02</ns2:Token>
         </ns2:SendResult>
      </ns2:SendResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

这是我用来读取XML的代码(变量xmlString包含上面的XML):

This the code that I'm using to read the XML (Variable xmlString contains the XML above):

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(is);

System.out.println("Element :" + doc.getElementsByTagName("Token").item(0));
System.out.println("Element :" + doc.getElementsByTagName("ns2:Token").item(0));

输出:

Element :null
Element :[ns2:Token: null]

如果我使用 ns2:Token作为标记名称,则可以读取该元素,但是我不希望在代码中使用该前缀,因为我不确定该前缀是否相同或更改未来。是否可以在不对标记名称中的命名空间进行硬编码的情况下读取xml元素?

I'm able to read the element if I use "ns2:Token" as the tag name, but I don't want to use the prefix in my code as I'm not sure if it'll be the same or change in the future. Is there any way to read the xml element without hard-coding the namespace in the tag name?

推荐答案

用于命名空间元素的W3C dom 方法:

getElementsByTagNameNS

NodeList getElementsByTagNameNS(String namespaceURI,
                                String localName)

    Returns a NodeList of all the Elements with a given local name and namespace URI in document order.

    Parameters:
        namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
        localName - The local name of the elements to match on. The special value "*" matches all local names. 
    Returns:
        A new NodeList object containing all the matched Elements.
    Since:
        DOM Level 2

IIRC的W3C DOM的早期版本对名称空间的支持较差,因此我不使用它。但是,如果将以上内容与完整的命名空间URI http://schemas.xmlsoap.org/soap/envelope/ 结合使用,则它应该可以工作。前缀并不重要-它在使用该文档之外没有永久性。

IIRC earlier version of the W3C DOM had poor support for namespaces so I don't use it. However if you use the above with the full namespaceURI http://schemas.xmlsoap.org/soap/envelope/ it should work. The prefix is unimportant - it has no permanency outside the document it is used in.

因此,请尝试:

System.out.println("Element :" + doc.getElementsByTagNameNS(
        "http://schemas.xmlsoap.org/soap/envelope/", "Token").item(0));

这篇关于无法使用DOM解析器读取具有名称空间前缀的xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆