DataContractSerializer 创建的 XML 的格式

发布于 2024-07-17 07:54:53 字数 463 浏览 5 评论 0 原文

有没有一种简单的方法可以让 DataContractSerializer 吐出格式化的 XML 而不是一个长字符串? 我不想以任何方式更改标签或内容,只是添加换行符和缩进以使 XML 更具可读性?

<tagA>
   <tagB>This is</tagB>   
   <tagC>Much</tagC>
   <tagD>
      <tagE>easier to read</tagE>
   </tagD>
</tagA>


<tagA><tagB>This is</tagB><tagC>Much</tagC><tagD><tagE>harder to read</tagE></tagD></tagA>

Is there an easy way to get DataContractSerializer to spit out formatted XML rather then one long string? I don't want to change the tags or content in any way, just have it add line breaks and indentation to make the XML more readable?

<tagA>
   <tagB>This is</tagB>   
   <tagC>Much</tagC>
   <tagD>
      <tagE>easier to read</tagE>
   </tagD>
</tagA>


<tagA><tagB>This is</tagB><tagC>Much</tagC><tagD><tagE>harder to read</tagE></tagD></tagA>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灰色世界里的红玫瑰 2024-07-24 07:54:53

正如 Bendewey 所说,XmlWriterSettings 就是您所需要的 - 例如类似的东西

var ds = new DataContractSerializer(typeof(Foo));

var settings = new XmlWriterSettings { Indent = true };

using (var w = XmlWriter.Create("fooOutput.xml", settings))
    ds.WriteObject(w, someFoos);

As bendewey says, XmlWriterSettings is what you need - e.g. something like

var ds = new DataContractSerializer(typeof(Foo));

var settings = new XmlWriterSettings { Indent = true };

using (var w = XmlWriter.Create("fooOutput.xml", settings))
    ds.WriteObject(w, someFoos);
鲜血染红嫁衣 2024-07-24 07:54:53

查看 Indent 属性>XmlWriterSettings

更新: 这是来自 MSDN 的一个很好的链接 如何:在 XmlWriter 上指定输出格式

此外,这里是一个示例:

class Program
{
    static void Main(string[] args)
    {
        var Mark = new Person()
        {
            Name = "Mark",
            Email = "[email protected]"
        };

        var serializer = new DataContractSerializer(typeof(Person));

        var settings = new XmlWriterSettings()
        {
            Indent = true,
            IndentChars = "\t"
        };

        using (var writer = XmlWriter.Create(Console.Out, settings))
        {
            serializer.WriteObject(writer, Mark);
        }
        Console.ReadLine();
    }
}
public class Person
{
    public string Name { get; set; }
    public string Email { get; set; }
}

Take a look at the Indent property of the XmlWriterSettings

Update: Here is a good link from MSDN on How to: Specify the Output format on the XmlWriter

Additionally, here is a sample:

class Program
{
    static void Main(string[] args)
    {
        var Mark = new Person()
        {
            Name = "Mark",
            Email = "[email protected]"
        };

        var serializer = new DataContractSerializer(typeof(Person));

        var settings = new XmlWriterSettings()
        {
            Indent = true,
            IndentChars = "\t"
        };

        using (var writer = XmlWriter.Create(Console.Out, settings))
        {
            serializer.WriteObject(writer, Mark);
        }
        Console.ReadLine();
    }
}
public class Person
{
    public string Name { get; set; }
    public string Email { get; set; }
}
小伙你站住 2024-07-24 07:54:53

调整 XML 文档中的空格时要小心! 调整空格将使 XML 对我们人类来说更易读,但可能会干扰机器解析。

根据 XML 标准,默认情况下空格很重要。 换句话说,就 XML 而言,空白就是内容

如果将格式良好的 XML 提供给 XML Document 对象,您将得到与其中没有空格或换行符的版本不同的结果。 您将获得添加到已格式化的版本中的其他文本节点。

这篇关于 XML 空白 的 MSDN 文章提供了几个示例,展示了白色空间有多么棘手空间还可以。

如果您只是为了人类使用而格式化 XML,那么这并不重要。 但如果您尝试往返格式化文档,则可能会遇到麻烦。

由于使用 DataContractSerializer 的主要好处之一是能够无缝地序列化对象和反序列化 XML,因此通常最好不要处理丑陋的输出。

当我想出于调试目的读取输出时,我通常将输出粘贴到 NotePad++ 中并在其上运行 XML-tidy 宏。

Be careful about adjusting whitespace in XML documents! Adjusting whitespace will make the XML more readable for us humans, but it may interfere with machine parsing.

According to the XML standard, whitespace is significant by default. In other words, as far as XML is concerned, white space is content.

If you feed your nicely formatted XML into an XML Document object, you will get a different result than the version that has no spaces or line breaks in it. You will get additional text nodes added to the version that has been formatted.

This MSDN article on XML White Space has several examples that show how tricky white space can be.

If you're formatting the XML only for human consumption, it doesn't matter. But if you try to round-trip your formatted document, you could run into trouble.

Since one of the key primary benefits of using DataContractSerializer is the ability to serialize objects and deserialize XML seamlessly, it's usually best to leave the ugly output alone.

I usually paste the output into NotePad++ and run an XML-tidy macro over it when I want to read it for debugging purposes.

巷雨优美回忆 2024-07-24 07:54:53
    public static string SerializeEntity<T>(T source)
    {
        using (MemoryStream ms = new MemoryStream())
        {

                NetDataContractSerializer serializer = new NetDataContractSerializer();
                serializer.Serialize(ms, source);
                return System.Text.Encoding.ASCII.GetString(ms.ToArray());

        }
    }

    public static T DeSerializeEntity<T>(string xml)
    {
        using (MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(xml)))
        {
                NetDataContractSerializer serializer = new NetDataContractSerializer();
                return (T)serializer.Deserialize(ms);
        }
    }
    public static string SerializeEntity<T>(T source)
    {
        using (MemoryStream ms = new MemoryStream())
        {

                NetDataContractSerializer serializer = new NetDataContractSerializer();
                serializer.Serialize(ms, source);
                return System.Text.Encoding.ASCII.GetString(ms.ToArray());

        }
    }

    public static T DeSerializeEntity<T>(string xml)
    {
        using (MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(xml)))
        {
                NetDataContractSerializer serializer = new NetDataContractSerializer();
                return (T)serializer.Deserialize(ms);
        }
    }
等你爱我 2024-07-24 07:54:53

基于此处发布的使用 XmlWriter 的其他示例,这里有一个版本(来自 http://ClipFlair.codeplex.com )与流(特别是 Ionic.Zip 库)一起使用,并且还显示了当您不应用格式时代码的情况(使用条件编译 - 只需注释掉 #define 以使其写入未格式化的 XML)

#define WRITE_FORMATTED_XML

using System.Xml;

namespace ClipFlair.Windows
{

  public partial class BaseWindow : FloatingWindow
  {

    //...

    #if WRITE_FORMATTED_XML
    private static XmlWriterSettings XML_WRITER_SETTINGS = new XmlWriterSettings() { Indent=true, IndentChars="  "};
    #endif

    //...

    public virtual void SaveOptions(ZipFile zip, string zipFolder = "") //THIS IS THE CORE SAVING LOGIC
    {
      if (SavingOptions != null) SavingOptions(this, null); //notify any listeners

      View.Busy = true;
      try
      {
        ZipEntry optionsXML = zip.AddEntry(zipFolder + "/" + View.GetType().FullName + ".options.xml",
          new WriteDelegate((entryName, stream) =>
          {
            DataContractSerializer serializer = new DataContractSerializer(View.GetType()); //assuming current View isn't null
            #if WRITE_FORMATTED_XML
            using (XmlWriter writer = XmlWriter.Create(stream, XML_WRITER_SETTINGS))
              serializer.WriteObject(writer, View);
            #else
            serializer.WriteObject(stream, View);
            #endif
          }));
      }
      catch (Exception e)
      {
        MessageBox.Show("ClipFlair options save failed: " + e.Message); //TODO: find the parent window
      }
      finally
      {
        View.Busy = false; //in any case (error or not) clear the Busy flag
      }

      if (SavedOptions != null) SavedOptions(this, null); //notify any listeners
    }

    //...

  }

}

based on the other samples posted here that use XmlWriter, here's a version (from http://ClipFlair.codeplex.com) that works with streams (and Ionic.Zip library in specific) and also shows how the code is when you don't apply formatting (using conditional compilation - just comment out the #define to make it write unformatted XML)

#define WRITE_FORMATTED_XML

using System.Xml;

namespace ClipFlair.Windows
{

  public partial class BaseWindow : FloatingWindow
  {

    //...

    #if WRITE_FORMATTED_XML
    private static XmlWriterSettings XML_WRITER_SETTINGS = new XmlWriterSettings() { Indent=true, IndentChars="  "};
    #endif

    //...

    public virtual void SaveOptions(ZipFile zip, string zipFolder = "") //THIS IS THE CORE SAVING LOGIC
    {
      if (SavingOptions != null) SavingOptions(this, null); //notify any listeners

      View.Busy = true;
      try
      {
        ZipEntry optionsXML = zip.AddEntry(zipFolder + "/" + View.GetType().FullName + ".options.xml",
          new WriteDelegate((entryName, stream) =>
          {
            DataContractSerializer serializer = new DataContractSerializer(View.GetType()); //assuming current View isn't null
            #if WRITE_FORMATTED_XML
            using (XmlWriter writer = XmlWriter.Create(stream, XML_WRITER_SETTINGS))
              serializer.WriteObject(writer, View);
            #else
            serializer.WriteObject(stream, View);
            #endif
          }));
      }
      catch (Exception e)
      {
        MessageBox.Show("ClipFlair options save failed: " + e.Message); //TODO: find the parent window
      }
      finally
      {
        View.Busy = false; //in any case (error or not) clear the Busy flag
      }

      if (SavedOptions != null) SavedOptions(this, null); //notify any listeners
    }

    //...

  }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文