我有一行单行
String s = "<Item><productname>COOLER MASTER Hyper 212 EVO RR-212E-20PK-R2
</productname><Price>$33.99</Price><ItemID>1000</ItemID></Item>";
在上面的字符串里面,在“&gt;”之后新行应该开始,所需的输出应该像
<Item>
<productname>COOLER MASTER Hyper 212 EVO RR-212E-20PK-R2 </productname>
<Price>$33.99</Price>
<ItemID>1000</ItemID>
</Item>
答案 0 :(得分:2)
试试这个:
String newString = s.replaceAll("><", ">\n <");
欢呼声
答案 1 :(得分:1)
这是一个JDOM示例:
String input = "...";
Document document = new SAXBuilder().build(new ByteArrayInputStream(input.getBytes()));
ByteArrayOutputStream pretty = new ByteArrayOutputStream();
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(document, pretty);
System.out.println(pretty.toString());
这个网站有一些很好的例子,说明如何以其他方式做到这一点:
http://www.chipkillmar.net/2009/03/25/pretty-print-xml-from-a-dom/
答案 2 :(得分:0)
另一种选择是解析XML,并使用OutputKeys.INDENT类的Transformer选项输出格式化的XML。
以下示例
Source source = new StreamSource(new StringReader(s));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 4);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
String xmlOutput = result.getWriter().toString();
System.out.println(xmlOutput);
String xmlOutput = result.getWriter().toString();
System.out.println(xmlOutput);
生成
以下的输出<?xml version="1.0" encoding="UTF-8"?>
<Item>
<productname>COOLER MASTER Hyper 212 EVO RR-212E-20PK-R2</productname>
<Price>$33.99</Price>
<ItemID>1000</ItemID>
</Item>