我有一个这样的XML字符串:

<?xml version='1.0'?><response><error code='1'> Success</error></response>

一个元素和另一个元素之间没有行,因此很难阅读。我想要一个函数格式化上面的字符串:

<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response> 

不需要自己手动编写格式函数,是否有任何。net库或代码片段我可以立即使用?


当前回答

可以使用XmlWriter通过流转换来漂亮地打印XML字符串。XmlReader WriteNode(真正的)。这个方法

将所有内容从读取器复制到写入器,并将读取器移动到下一个同级的开始。

定义以下扩展方法:

public static class XmlExtensions
{
    public static string FormatXml(this string xml, bool indent = true, bool newLineOnAttributes = false, string indentChars = "  ", ConformanceLevel conformanceLevel = ConformanceLevel.Document) => 
        xml.FormatXml( new XmlWriterSettings { Indent = indent, NewLineOnAttributes = newLineOnAttributes, IndentChars = indentChars, ConformanceLevel = conformanceLevel });

    public static string FormatXml(this string xml, XmlWriterSettings settings)
    {
        using (var textReader = new StringReader(xml))
        using (var xmlReader = XmlReader.Create(textReader, new XmlReaderSettings { ConformanceLevel = settings.ConformanceLevel } ))
        using (var textWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(textWriter, settings))
                xmlWriter.WriteNode(xmlReader, true);
            return textWriter.ToString();
        }
    }
}

现在你可以做:

var inXml = @"<?xml version='1.0'?><response><error code='1'> Success</error></response>";
var newXml = inXml.FormatXml(indentChars : "", newLineOnAttributes : false); // Or true, if you prefer
Console.WriteLine(newXml);

的打印

<?xml version='1.0'?>
<response>
<error code="1"> Success</error>
</response>

注:

Other answers load the XML into some Document Object Model such as XmlDocument or XDocument/XElement, then re-serialize the DOM with indentation enabled. This streaming solution completely avoids the added memory overhead of a DOM. In your question you do not add any indentation for the nested <error code='1'> Success</error> node, so I set indentChars : "". Generally an indentation of two spaces per level of nesting is customary. Attribute delimiters will be unconditionally transformed to double-quotes if currently single-quotes. (I believe this is true of other answers as well.) Passing conformanceLevel : ConformanceLevel.Fragment allows strings containing sequences of XML fragments to be formatted. Other than ConformanceLevel.Fragment, the input XML string must be well-formed. If it is not, XmlReader will throw an exception.

这里是小样。

其他回答

你必须以某种方式解析内容。我发现使用LINQ是最简单的方法。同样,这完全取决于您的具体场景。下面是一个使用LINQ格式化输入XML字符串的示例。

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

[为简洁起见,省略使用语句]

来自kristopherjohnson的这条就好多了:

It doesn't require an XML document header either. Has clearer exceptions Adds extra behaviour options: OmitXmlDeclaration = true, NewLineOnAttributes = true Less lines of code static string PrettyXml(string xml) { var stringBuilder = new StringBuilder(); var element = XElement.Parse(xml); var settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.NewLineOnAttributes = true; using (var xmlWriter = XmlWriter.Create(stringBuilder, settings)) { element.Save(xmlWriter); } return stringBuilder.ToString(); }

如果你加载XMLDoc,我很确定. tostring()函数对此有重载。

但是这是用来调试的吗?这样发送的原因是为了占用更少的空间(即从XML中剥离不必要的空白)。

格式化一个XML文件,使它在c#中看起来更好

// Format the XML text.
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml_document.WriteTo(xml_text_writer);

// Display the result.
txtResult.Text = string_writer.ToString();

如何漂亮地打印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;
}