-5

i have a string in single line

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

inside the above string , after the ">" new line should started and required output should like

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

3 Answers3

2

Try this:

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

cheers

peshkira
  • 6,069
  • 1
  • 33
  • 46
1

you're probably best off with a pretty printer here, since that's what you're really trying to do. W3C, Xerces, JDOM, etc... all have output capability that allows you to read in xml, and spit it out pretty printed.

Here's a JDOM Example:

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());

This site has some good examples of how to do it in other ways:

http://www.chipkillmar.net/2009/03/25/pretty-print-xml-from-a-dom/

Matt
  • 11,523
  • 2
  • 23
  • 33
0

Another option is to parse the XML, and use the OutputKeys.INDENT option of the Transformer class to output the XML formatted.

The following example

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

produces the output below

<?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>
Garett
  • 16,632
  • 5
  • 55
  • 63