我有以下 XML 字符串,我想将此字符串转换为 org.w3c.dom.Document,以便获取“CallPaySecureResult”元素的值。
<?xml version="1.0" encoding="UTF-8"?>
<S:Body xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<ns2:CallPaySecureResponse xmlns:ns2="https://paysecure/merchant.soap/">
<CallPaySecureResult>&lt;status&gt;success&lt;/status&gt;&lt;errorcode&gt;0&lt;/errorcode&gt;&lt;errormsg /&gt;&lt;guid&gt;d785f819-6fc1-1c68-8edf-bbb65cba5412&lt;/guid&gt;&lt;/paysecure&gt;</CallPaySecureResult>
</ns2:CallPaySecureResponse>
</S:Body>
我尝试过以下代码
public String processIssuerResultParameters(String strXML)throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc=null;
String CallPaySecureResult ="";
try
{
builder = factory.newDocumentBuilder();
doc = builder.parse( new InputSource( new StringReader( strXML ) ) );
logger.severe(doc.getTextContent());
} catch (Exception e) {
return "1:"+e.toString()+doc.getTextContent();
}
}
我已经尝试过这个:
InputSource is= new InputSource(new StringReader(strXML));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
builder = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(is);
还有这个:
Source source = new StreamSource(new StringReader(strXML));
DOMResult result = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(source , result);
doc = (Document) result.getNode();
但在所有情况下变量“doc”均为空。
如何将 XML(字符串)解析为文档并获取 <CallPaySecureResult>
中的值?
最佳答案
这里有一些示例+上下文。
private static Document transformToDocument(Object document) {
try {
String docString;
if (document instanceof ReaderResource) {
docString = ((ReaderResource) document).getContent();
} else if (document instanceof String) {
docString = (String) document;
} else if (document instanceof Element) { //used?
DOMSource domSource = new DOMSource((Element) document);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
Properties properties = new Properties();
properties.setProperty(OutputKeys.METHOD, "xml");
properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperties(properties);
transformer.transform(domSource, result);
docString = writer.toString();
} else {
return null;
}
InputStream is = new ByteArrayInputStream(docString.getBytes());
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
关于javascript - 将 XML 字符串转换为 org.w3c.dom.Document?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35889416/