-5

我在单行中有一个字符串

String s = "<Item><productname>COOLER MASTER Hyper 212 EVO RR-212E-20PK-R2
</productname><Price>$33.99</Price><ItemID>1000</ItemID></Item>";

在上面的字符串中,在“>”之后应该开始新行并且所需的输出应该像

<Item>
 <productname>COOLER MASTER Hyper 212 EVO RR-212E-20PK-R2 </productname>
 <Price>$33.99</Price> 
 <ItemID>1000</ItemID>
</Item>
4

3 回答 3

2

试试这个:

String newString = s.replaceAll("><", ">\n <");

干杯

于 2012-06-08T12:40:50.967 回答
1

您可能最好在这里使用漂亮的打印机,因为这就是您真正想要做的事情。W3C、Xerces、JDOM 等等……都有输出能力,可以让你读入 xml,然后把它打印出来。

这是一个 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/

于 2012-06-08T13:05:59.997 回答
0

另一种选择是解析 XML,并使用Transformer类的OutputKeys.INDENT选项输出格式化的 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>
于 2012-06-08T13:07:45.483 回答