我正在嘗試創建一個包含遵循特定格式的 XML 的 SOAPMessage,以前我曾嘗試將已經生成的 XML 作為字串,但是它會將“>”和“<”字符轉換為 > 和<,端點沒有正確驗證。我設法將 XML 作為一個節點放在一個檔案中,它可以作業,但是,現在 XML 中確實有值的 xmlns 屬性變成了空的。例如,給定以下訊息:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Example xmlns="https://www.example.com"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
xmlns="https://www.example.com"
結束為,這xmlns=""
對端點無效。我現在的代碼是:
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody soapBody = envelope.getBody();
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.newDocument();
Node node = db.parse(new InputSource(new StringReader(xmlString))).getDocumentElement();
Node newNode = node.cloneNode(true);
document.adoptNode(newNode);
document.appendChild(newNode);
soapBody.addDocument(document);
soapMessage.saveChanges();
return soapMessage;
我已經嘗試記錄 SOAPMessage 和自始至終使用的節點以查看任何更改,并且 xmlns 總是有一個值。我的下一個想法是一個一個地添加帶有 xmlns 的節點,這樣我就可以手動設定屬性,但是考慮到我已經不得不將 XML 添加為單個節點的方法,這看起來很復雜,并且生成的代碼最終可能是真的令人費解。我需要知道是否有人對為什么會發生這種情況以及如何以更簡單的方式解決它有任何線索或想法。
uj5u.com熱心網友回復:
通過創建此方法解決了它:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try{
factory.setNamespaceAware(true);
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlString ) ) );
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532254.html
標籤:爪哇xml肥皂