简体   繁体   中英

Parsing with XPath a xml document. Why add a <xml tag as a header> in the result?

I searched on google first and I found many result about how to parse with xpath a xml document. I have parse it but a want to convert a NODELIST in String and I have created a method for it:

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;
}

This method works perfectly but the transformer adds an <?xml version="1.0" encoding="UTF-8"?> in the header of the result, and I don't want that. This is the result of the method:

<?xml version="1.0" encoding="UTF-8"?>
<xmlTagToTrasform>
  <xmlTagToTrasform2>
        .
        .
        .
        .
  </xmlTagToTrasform2>
</xmlTagToTrasform>

在调用transform之前,可以将变换器配置为不输出XML声明:

serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

XML is a markup language and every xml document has this line on the top to specify the version and the encoding-type. It is madatory to have this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM