[英]Replace XML element with Java
在下面的XML中,我想使用Java更改<Password>元素的值。
<?xml version="1.0" encoding="UTF-8"?>
<ns1:Envelope xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns2="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<ns1:Header>
<ns2:Security>
<ns2:UsernameToken xmlns:ns3="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<ns2:Username>ADMIN</ns2:Username>
<ns2:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">abcd</ns2:Password>
<ns3:Created>2016-09-08T17:47:05.079Z</ns3:Created>
</ns2:UsernameToken>
</ns2:Security>
</ns1:Header>
<ns1:Body>
</ns1:Body>
</ns1:Envelope>
我嘗試使用以下代碼:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("D:/test.xml"));
Element root = doc.getDocumentElement();
root.getElementsByTagName("Password").item(0).setTextContent("efgh");
但我得到NullPointerException。 這是因為getElementsByTagName返回一個包含0個元素的NodeList。 我嘗試使用getElementsByTagNameNS,但結果仍然相同。
root.getElementsByTagNameNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password").item(0).setTextContent("efgh");
我還可以做些什么? 提前致謝。
您需要將DocumentBuilderFactory
設置為名稱空間感知:
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("D:/test.xml"));
Element root = doc.getDocumentElement();
root.getElementsByTagNameNS("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Password").item(0).setTextContent("efgh");
// Write out result to check it
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.