1
在下面的XML中,我想要使用Java更改<密碼>元素的值。使用Java替換XML元素
<?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");
我還能做什麼?提前致謝。
如果你嘗試過什麼'root.getElementsByTagName( 「NS2:密碼」)'代替? – n247s
這將工作,但問題是前綴不一定是「ns2」。 XML由JAXB生成,可以分配任何所需的前綴。 – user3573403