如何访问SOAP消息元素?

时间:2017-01-25 18:37:11

标签: java xml xpath soap

所以我试图在包含SOAP消息的XML文件中替换用户名和密码的值。以下是要素:

 <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
        <o:UsernameToken u:Id="uuid-68f84594-d592-470b-9bbc-b29f58b4756f-1">
            <o:Username></o:Username>
            <o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"></o:Password>
        </o:UsernameToken>
    </o:Security>

基本上,我想从配置文件中获取用户名和密码值,并将它们放在包含soap消息的XML文件中的用户名和密码字段中。这是我的尝试,它会在docElement.getElementsByTagName行抛出一个NPE:

 public void updateUserDetails() {
    final Properties configProperties = new Properties();
    try {
        configProperties.load(new FileInputStream(PROPERTIES));
        final Document requestDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream(SOAP_REQUEST));
        final Element docElement = requestDoc.getDocumentElement();
        docElement.getElementsByTagName("Username").item(0).setTextContent(configProperties.getProperty("username"));
        docElement.getElementsByTagName("Password").item(0).setTextContent(configProperties.getProperty("password"));
    } catch(IOException | ParserConfigurationException | SAXException exception) {
        LOGGER.error("There was an error loading the properties file", exception);
    }
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

它似乎与名称空间问题有关。 尝试为您的代码指定命名空间:

String namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
final Document requestDoc = factory.newDocumentBuilder().parse(new FileInputStream(SOAP_REQUEST));
docElement.getElementsByTagNameNS(namespace, "Username").item(0).setTextContent(configProperties.getProperty("username"));
docElement.getElementsByTagNameNS(namespace, "Password").item(0).setTextContent(configProperties.getProperty("password"));

另外,最后不要忘记将结果写回文件:

TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
Transformer transformer = transformerFactory.newTransformer(); 
DOMSource domSource = new DOMSource(requestDoc); 
StreamResult streamResult = new StreamResult(new File(SOAP_REQUEST)); 
transformer.transform(domSource, streamResult);