我有一个这样的XML字符串:
<?xml version='1.0'?><response><error code='1'> Success</error></response>
一个元素和另一个元素之间没有行,因此很难阅读。我想要一个函数格式化上面的字符串:
<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response>
不需要自己手动编写格式函数,是否有任何。net库或代码片段我可以立即使用?
如何漂亮地打印XML(不幸的是,该链接现在返回404:()
链接中的方法以XML字符串作为参数,并返回格式良好(缩进)的XML字符串。
我只是从链接中复制了示例代码,以使这个回答更全面和方便。
public static String PrettyPrint(String XML)
{
String Result = "";
MemoryStream MS = new MemoryStream();
XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode);
XmlDocument D = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
D.LoadXml(XML);
W.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
D.WriteContentTo(W);
W.Flush();
MS.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
MS.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader SR = new StreamReader(MS);
// Extract the text from the StreamReader.
String FormattedXML = SR.ReadToEnd();
Result = FormattedXML;
}
catch (XmlException)
{
}
MS.Close();
W.Close();
return Result;
}