C#:一种将单行 XML 文件带入人类可读多行的简单方法 [英] C#: A simple way to bring One-line-XML-files to human readable multi line

查看:13
本文介绍了C#:一种将单行 XML 文件带入人类可读多行的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法,将带有一行而没有换行符的 xml 文件转换为 C# 中良好的结构化人类可读版本.System.XML 或小型开源框架中是否已有任何实现或实现它的最佳实践?

例如.转换此 XML 字符串:

<预><代码><Root><Node id="1"><Childnode>Text</Childnode></Node><Node id="2">Text<Kid name="jack"/<<;/节点>

<预><代码><根><节点 id="1"><子节点>文本</子节点></节点><节点 id="2">文本<Kid name="jack"/></节点></Root>

解决方案

如果您有 .NET 3.5:

XDocument 文档 = XDocument.Load(filename);文档.保存(文件名);

这会自动缩进.请注意,它不会像您提出的问题那样做,因为您只是缩进了某些节点.那会更棘手.

如果您坚持使用 .NET 2.0,这里是 Craig 的方法,重新调整并更改为使用文件而不是字符串:

public static void FormatXmlString(string inputFile, string outputFile){XmlDocument 文档 = 新 XmlDocument();文件.加载(输入文件);XmlWriterSettings settings = new XmlWriterSettings();settings.Indent = true;使用 (XmlWriter writer = XmlWriter.Create(outputFile, settings)){document.WriteTo(writer);}}

使用 C# 3 的 XmlWriterSettings 但可能只是:

new XmlWriterSettings { Indent = true }

它可以嵌入到对 XmlWriter.Create 的调用中,但如果您使用的是 .NET 2.0,则您可能不能使用 C# 3.

如果输入文件名部分导致问题,您可以使用:

XmlDocument 文档 = new XmlDocument();使用 (Stream stream = File.OpenRead(inputFile)){文件.加载(流);}

I'm looking for a simply way to bring a xml-File with one line without line feeds to a good structured human readable version in C#. Is there any Implementation already in System.XML or a tiny open source framework or a best practice for implementing it?

ex. transform this XML-String:


<Root><Node id="1"><Childnode>Text</Childnode></Node><Node id="2">Text<Kid name="jack" /></Node></Root>

to


<Root>
  <Node id="1">
    <Childnode>
      Text
    </Childnode>
  </Node>
  <Node id="2">
    Text
    <Kid name="jack" />
  </Node>
</Root>

解决方案

If you have .NET 3.5:

XDocument document = XDocument.Load(filename);
document.Save(filename);

This will indent automatically. Note that it won't do quite as your question asked, because you're only indenting some of the nodes. That's going to be trickier.

If you're stuck with .NET 2.0, here's Craig's method rejigged and changed to use files instead of strings:

public static void FormatXmlString(string inputFile, string outputFile)
{
    XmlDocument document = new XmlDocument();
    document.Load(inputFile);
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(outputFile, settings))
    {
        document.WriteTo(writer);
    }
}

With C# 3 the XmlWriterSettings but could just be:

new XmlWriterSettings { Indent = true }

which could be embedded in the call to XmlWriter.Create, but if you're using .NET 2.0 you probably can't use C# 3.

EDIT: If the input filename part causes a problem, you can use:

XmlDocument document = new XmlDocument();
using (Stream stream = File.OpenRead(inputFile))
{
    document.Load(stream);
}

这篇关于C#:一种将单行 XML 文件带入人类可读多行的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆