2016-11-22 10 views
1

以下のXMLでは、Javaを使用してパスワード>要素の値を変更したいと考えています。XML要素を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"); 

他に何ができますか?前もって感謝します。

+0

( "NS2:パスワードを")'の代わりに? – n247s

+0

これは動作しますが、問題は接頭辞が必ず「ns2」であるとは限りません。 XMLはJAXBによって生成され、任意の接頭辞を割り当てることができます。 – user3573403

答えて

0

はあなたのDocumentBuilderFactoryが名前空間を認識する設定する必要があります:あなたは `root.getElementsByTagNameしようとした場合、どう

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); 
} 
+0

ありがとうございます。これは機能します。 – user3573403

関連する問題