我正在尝试从HttpServletRequest读取xml字符串,如下所示:
private String getPayload(HttpServletRequest httRequest, String contentType){
StringBuilder buffer = new StringBuilder();
String data = null, payload = null;
BufferedReader bufferedReader = null;
try {
bufferedReader = httRequest.getReader();
String line;
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
data = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Payload data: " + data);
}
这给了我一个字符串:
<?xml version="1.0" encoding="UTF-8"?><sgn> <nev> <rep> <cin rn="cin227"> <ty>4</ty> <ri>R241</ri> <pi>R7</pi> <ct>2016-10-27T18:23:49</ct> <lt>2016-10-27T18:23:49</lt> <et>2016-11-27T18:23:49</et> <at>erer</at> <aa>name</aa> <st>17</st> <cs>88</cs> <con>Sid-Container-Element</con> </cin> </rep> <net>3</net> </nev> <sur>R7/R8</sur> <cr>C1</cr></sgn>
所以它没有缩进。我尝试了几点来缩进它,比如:
XPathFactory xpathFactory = XPathFactory.newInstance();
// XPath to find empty text nodes.
XPathExpression xpathExp = xpathFactory.newXPath().compile(
"//text()[normalize-space(.) = '']");
NodeList emptyTextNodes = (NodeList)
xpathExp.evaluate(doc, XPathConstants.NODESET);
// Remove each empty text node from document.
for (int i = 0; i < emptyTextNodes.getLength(); i++) {
Node emptyTextNode = emptyTextNodes.item(i);
emptyTextNode.getParentNode().removeChild(emptyTextNode);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
首先使用xpath删除空格,然后应用变换器。所以这仍然没有给我正确的输出:
<?xml version="1.0" encoding="UTF-8"?><sgn >
<nev>
<rep>
<cin rn="cin227">
<ty>4</ty>
<ri>R241</ri>
<pi>R7</pi>
<ct>2016-10-27T18:23:49</ct>
<lt>2016-10-27T18:23:49</lt>
<et>2016-11-27T18:23:49</et>
<at>erer</at>
<aa>name</aa>
<st>17</st>
<cs>88</cs>
<con>Sid-Container-Element</con>
</cin>
</rep>
<net>3</net>
</nev>
<sur>R7/R8</sur>
<cr>C1</cr>
</sgn>
所以它没有正确地缩进它。我想要适当的缩进。
我在这里做错了什么?