用Java替换XML元素

时间:2016-11-22 05:27:59

标签: java xml dom xml-parsing

在下面的XML中,我想更改< Password>的值。使用Java的元素。

<?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");

我还能做什么?提前谢谢。

1 个答案:

答案 0 :(得分:0)

您需要将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);
}