防止 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 格式化输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)