Format Xml String

Format XML string to print friendly XML string

You will have to parse the content somehow ... I find using LINQ the most easy way to do it. Again, it all depends on your exact scenario. Here's a working example using LINQ to format an input XML string.

string FormatXml(string xml)
{
try
{
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception)
{
// Handle and throw if fatal exception here; don't just ignore them
return xml;
}
}

[using statements are ommitted for brevity]

How to pretty print XML from Java?

Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.

import org.w3c.dom.Node;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;

/**
* Pretty-prints xml, supplied as a string.
* <p/>
* eg.
* <code>
* String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
* </code>
*/
public class XmlFormatter {

public String format(String xml) {

try {
final InputSource src = new InputSource(new StringReader(xml));
final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml"));

//May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");

final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
final LSSerializer writer = impl.createLSSerializer();

writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified.
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted.

return writer.writeToString(document);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
String unformattedXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
" xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
" xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
" <Query>\n" +
" <query:CategorySchemeWhere>\n" +
" \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
" </query:CategorySchemeWhere>\n" +
" </Query>\n\n\n\n\n" +
"</QueryMessage>";

System.out.println(new XmlFormatter().format(unformattedXml));
}
}

How to format an XML string with line breaks using Javascript?

If there is no text between the xml-tags like in the example you presented (e.g. <foo><bar></foo> and not <foo>Some Text</foo>) one can simply do the following:

xmlStr.replaceAll(">",">\n")

which results in

<?xml version="1.0"?>
<?meta name="test"?>
<Foo>
<Bar>
<FooBar/>
</Bar>
</Foo>

How do I format XML in Notepad++?

Try Plugins -> XML Tools -> Pretty Print (libXML) or (XML only - with line breaks Ctrl + Alt + Shift + B)

You may need to install XML Tools using your plugin manager in order to get this option in your menu.

In my experience, libXML gives nice output but only if the file is 100% correctly formed.

format an xml string in Ruby

Use the REXML::Formatters::Pretty formatter:

require "rexml/document" 
source = '<some><nested><xml>value</xml></nested></some>'

doc = REXML::Document.new(source)
formatter = REXML::Formatters::Pretty.new

# Compact uses as little whitespace as possible
formatter.compact = true
formatter.write(doc, $stdout)

In C#, what is the best method to format a string as XML?

string unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>";
string formattedXml = XElement.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);

Output:

<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>

The Xml Declaration isn't output by ToString(), but it is by Save() ...

  XElement.Parse(unformattedXml).Save(@"C:\doc.xml");
Console.WriteLine(File.ReadAllText(@"C:\doc.xml"));

Output:

<?xml version="1.0" encoding="utf-8"?>
<book>
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>

Format XML string in VBScript

All credit goes to Robert McMurray; I just reworked his script into a function:

Option Explicit

' ****************************************
Function prettyXml(ByVal sDirty)
' ****************************************
' Put whitespace between tags. (Required for XSL transformation.)
' ****************************************
sDirty = Replace(sDirty, "><", ">" & vbCrLf & "<")
' ****************************************
' Create an XSL stylesheet for transformation.
' ****************************************
Dim objXSL : Set objXSL = WScript.CreateObject("Msxml2.DOMDocument")
objXSL.loadXML "<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">" & _
"<xsl:output method=""xml"" indent=""yes""/>" & _
"<xsl:template match=""/"">" & _
"<xsl:copy-of select="".""/>" & _
"</xsl:template>" & _
"</xsl:stylesheet>"
' ****************************************
' Transform the XML.
' ****************************************
Dim objXML : Set objXML = WScript.CreateObject("Msxml2.DOMDocument")
objXML.loadXml sDirty
objXML.transformNode objXSL
prettyXml = objXML.xml
End Function

Dim sTest : sTest = "<a><b><c/></b></a>"
WScript.Echo sTest
WScript.Echo "----------"
WScript.Echo prettyXml(sTest)
WScript.Quit 0

output:

cscript robmcm-2.vbs
<a><b><c/></b></a>
----------
<a>
<b>
<c/>
</b>
</a>

On 2nd thought:

You shouldn't use the above unless you have studied this.

how to generate formatted .xml file?

With some guessing and after looking at this question adding these lines
after obtaining the transformer might do the trick

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");


Related Topics



Leave a reply



Submit