防止 XmlSerializer 格式化输出

Prevent XmlSerializer from formatting output(防止 XmlSerializer 格式化输出)

本文介绍了防止 XmlSerializer 格式化输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用 XmlSerializer 的默认设置时,它会将 XML 输出为格式化值.

When using the default settings with the XmlSerializer it will output the XML as a formated value.

IE:类似的东西.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Stock>
    <ProductCode>12345</ProductCode>
    <ProductPrice>10.32</ProductPrice>
  </Stock>
  <Stock>
    <ProductCode>45632</ProductCode>
    <ProductPrice>5.43</ProductPrice>
  </Stock>
</ArrayOfStock>

如何防止输出中出现任何类型的格式化?所以我想要实现的就是这个.

How does one prevent any type of formatting on the output? So what I am looking to achieve is this.

<?xml version="1.0" encoding="utf-8"?><ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Stock><ProductCode>123456</ProductCode><ProductPrice>10.57</ProductPrice></Stock><Stock><ProductCode>789123</ProductCode><ProductPrice>133.22</ProductPrice></Stock></ArrayOfStock>

我的方法的完整代码是

public static String Serialize(Stock stock)
{
     XmlSerializer serializer = new XmlSerializer(typeof(Stock));

     using (StringWriter stringWriter = new StringWriter())
     {
         serializer.Serialize(stringWriter, stock);
         return stringWriter.ToString();
     }            
}

推荐答案

不是很直观,但是 XmlWriterSettings 上的 Indent 属性控制了整个格式:

Not very intuitive, but the Indent property on the XmlWriterSettings controls the whole formatting:

var serializer = new XmlSerializer(typeof(MyClass));

using (var writer = new StreamWriter("file.path"))
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = false }))
{
    serializer.Serialize(xmlWriter, myObject);
}

XmlWriterSettings 您可能想要探索.

There are a few more options on XmlWriterSettings that you might want to explore.

这篇关于防止 XmlSerializer 格式化输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:防止 XmlSerializer 格式化输出