本文介绍了格式化XML字符串列印XML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个XML字符串这样:
I have an XML string as such:
<?xml version='1.0'?><response><error code='1'> Success</error></response>
有一个元件和另一个,从而之间没有线是很难看的。我想要格式化上面的字符串的函数:
There are no lines between one element and another, and thus is very difficult to read. I want a function that formats the above string:
<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
没有求助于手动编写格式函数自己,有任何.NET库或code片段,我可以随便用?
Without resorting to manually write the format function myself, is there any .Net library or code snippet that I can use offhand?
推荐答案
使用XmlTextWriter的...
Use XmlTextWriter...
public static String PrintXML(String XML)
{
String Result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(XML);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
String FormattedXML = sReader.ReadToEnd();
Result = FormattedXML;
}
catch (XmlException)
{
}
mStream.Close();
writer.Close();
return Result;
}
这篇关于格式化XML字符串列印XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!