Format XML: output an XML string with indentation Effect

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.