格式化XML字符串以打印友好的XML字符串

Gra*_*ton 165 c# xml formatting

我有一个XML字符串:

<?xml version='1.0'?><response><error code='1'> Success</error></response>
Run Code Online (Sandbox Code Playgroud)

一个元素与另一个元素之间没有线条,因此很难阅读.我想要一个格式化上述字符串的函数:

<?xml version='1.0'?>
<response>
<error code='1'> Success</error>
</response> 
Run Code Online (Sandbox Code Playgroud)

如果不依靠自己手动编写格式函数,是否有任何我可以随意使用的.Net库或代码片段?

Cha*_*ari 293

您将不得不以某种方式解析内容...我发现使用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;
     }
 }
Run Code Online (Sandbox Code Playgroud)

[为简洁起见,省略了使用陈述]

  • @radim是的.不会对实际数据进行任何更改.只有标签将被格式化和缩进. (3认同)
  • 我注意到它适用于UTF8,但不适用于Unicode XML文件内容. (2认同)
  • 建议包括命名空间,因为它可以防止用户不得不去查找他们以前可能没有经常使用的类的命名空间。使用 System.Xml.Linq; 效果很好 谢谢! (2认同)

S M*_*ran 172

使用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)
    {
        // Handle the exception
    }

    mStream.Close();
    writer.Close();

    return result;
}
Run Code Online (Sandbox Code Playgroud)

  • 澄清Mike的评论:LINQ是在.NET 3.5中引入的.因此,如果您使用的是早于.NET的版本(.NET 1,1.1,2或3.0),那么您将不得不使用此答案.但是如果你使用.NET 3.5或更高版本,Charles Prakash Dasari的答案要简单得多. (8认同)
  • 如果你正在处理旧版本的.NET框架LINQ之前的代码,那么这种方法很有效,但另一个例子更清晰. (7认同)

Tod*_*odd 56

来自kristopherjohnson的这个更好:

  1. 它也不需要XML文档头.
  2. 有更明确的例外
  3. 添加额外的行为选项:OmitXmlDeclaration = true,NewLineOnAttributes = true
  4. 减少代码行数

    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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 与接受的答案相比.与Charles相比,这个具有更好的可配置性.但是我可能会在将来使用Charlies方法,这种可配置性将是一个罕见的要求. (3认同)

小智 8

对我有用的简单解决方案:

        XmlDocument xmlDoc = new XmlDocument();
        StringWriter sw = new StringWriter();
        xmlDoc.LoadXml(rawStringXML);
        xmlDoc.Save(sw);
        String formattedXml = sw.ToString();
Run Code Online (Sandbox Code Playgroud)


Cha*_* Im 6

检查以下链接:如何漂亮打印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;
}
Run Code Online (Sandbox Code Playgroud)

  • 对我很有用,我只是把它作为字符串的扩展方法.那个网站也关闭了,所以抓住一个副本很好...... (2认同)

小智 5

我试过:

internal static void IndentedNewWSDLString(string filePath)
{
    var xml = File.ReadAllText(filePath);
    XDocument doc = XDocument.Parse(xml);
    File.WriteAllText(filePath, doc.ToString());
}
Run Code Online (Sandbox Code Playgroud)

它按预期工作正常。