使用XPath解析xml文档。为什么在结果中添加<xml tag =“”as =“”a =“”header =“”>?</xml>

时间:2014-11-25 11:37:17

标签: java xml xpath

我先搜索谷歌,然后发现了很多关于如何用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>

2 个答案:

答案 0 :(得分:6)

在调用transform

之前,您可以将变换器配置为不输出XML声明
serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

答案 1 :(得分:-3)

XML是一种标记语言,每个xml文档都在顶部有这一行来指定版本和编码类型。有这个是疯了。