我首先在google上搜索,发现了很多关于如何使用xpath解析xml文档的结果。我已经解析了它,但是想在String中转换一个NODELIST,我为此创建了一个方法:
private String processResult(Document responseDocument) throws XPathExpressionException, TransformerException {
NodeList soaphead = responseDocument.getElementsByTagName("xmlTagToTrasform");
StringWriter sw = new StringWriter();
Transformer serializer = TransformerFactory.newInstance().newTransformer();
serializer.transform(new DOMSource(soaphead.item(0)), new StreamResult(sw));
String result = sw.toString();
return result;
}
此方法工作完美,但是转换器在结果的标题中添加了
<?xml version="1.0" encoding="UTF-8"?>
,我不希望这样。这是该方法的结果:<?xml version="1.0" encoding="UTF-8"?>
<xmlTagToTrasform>
<xmlTagToTrasform2>
.
.
.
.
</xmlTagToTrasform2>
</xmlTagToTrasform>
最佳答案
在调用transform
之前,可以配置转换器不输出XML声明:
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");