阻止XmlSerializer格式化输出

时间:2011-03-24 04:03:06

标签: c# xml formatting xml-serialization

在XmlSerializer中使用默认设置时,它会将XML输出为格式化值。

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>

如何防止输出上出现任何类型的格式?所以我想要实现的是这个。

<?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();
     }            
}

3 个答案:

答案 0 :(得分:29)

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

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上还有一些您可能想要探索的选项。

答案 1 :(得分:0)

...

XmlSerializer xmlser = new XmlSerializer(...);

XmlWriterSettings settings = new XmlWriterSettings {Indent = false};

using (XmlWriter xw = XmlWriter.Create(stream, settings))
{

...

答案 2 :(得分:0)

解析生成的XML并删除换行符和标签很简单...
使用'Indent = false',仍会将元素放在换行符上吗?