問題描述
這是輸入 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 命名空間元素的方法:
The W3C dom method for namespaced elements:
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 對命名空間的支持很差,所以我不使用它.但是,如果您將上述內容與完整的 namespaceURI 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!