Format XML: output an XML string with indentation effect
1. the following Code can be used to reformat an XML string:
private string formatxml (string source)
{< br> stringbuilder sb = new stringbuilder ();
xmltextwriter writer = NULL;
try
{< br> xmldocument Doc = new xmldocument ();
Doc. loadxml (source);
writer = new xmltextwriter (New stringwriter (SB);
writer. formatting = formatting. indented;
Doc. writeto (writer);
}< br> finally
{< br> If (writer! = NULL) writer. Close ();
}
Return sb. tostring ();
}
2. In some cases, if you need to apply the indent style to the attribute in the XML code, you can rewrite the writestartattribute method of the xmltextwriter class to achieve this:
Using system. IO;
Using system. text;
Using system. xml;
Namespace Test
{
Public class xmlreformatter: xmltextwriter
{
Private xmlreader XR;
Private readonly stringwriter SW;
Public xmlreformatter (stringwriter SW): Base (SW)
{
This. Sw = Sw;
}
Public override void writestartattribute (string prefix, string localname, string NS)
{
Stringbuilder sb = new stringbuilder ("\ r \ n ");
Int I = XR. depth;
For (I * = indentation; I> 0; I --) sb. append (indentchar );
Sw. Write (sb. tostring ());
Base. writestartattribute (prefix, localname, NS );
}
Public override void writenode (xmlreader reader, bool defattr)
{
Xr = reader;
Base. writenode (reader, defattr );
}
}
}
Call example:
Private string formatxmlattribute (string source)
{
Stringbuilder sb = new stringbuilder ();
Xmltextreader TR = new xmltextreader (New stringreader (source ));
Xmlreformatter formatter = new xmlreformatter (New stringwriter (SB ));
Formatter. Formatting = formatting. indented;
Formatter. writenode (TR, true );
Formatter. Flush ();
Formatter. Close ();
Tr. Close ();
Return sb. tostring ();
}