【发布时间】:2020-02-15 10:07:44
【问题描述】:
我需要将一个 c# 对象序列化为 xml,我可以像在格式化部分中那样做,但是我们可以在没有缩进/额外空格/新行的格式化的情况下实现它。这是必需的,因为我们需要将整个对象写入 csv,因此我们需要一个缩小版本。我尝试了几个 XmlWriterSettings,但没有按预期工作。任何代码 sn -p 都会有很大帮助,并且要序列化的对象可以具有其他引用类型作为可能从其他基类继承的成员,因此序列化程序可能需要已知类型
格式化的 XML:
<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>
无格式:
<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>
代码尝试:
Type[] _knownExpressions = new Type[]
{
typeof(SimpleExpression),
typeof(CompositeExpression)
};
string expression = string.Empty;
MemoryStream ms = new MemoryStream();
DataContractSerializer dcs = new DataContractSerializer(typeof(Expression), _knownExpressions);
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, System.Text.Encoding.Default))
{
xmlTextWriter.Formatting = Formatting.None;
dcs.WriteObject(xmlTextWriter, expression);
xmlTextWriter.Flush();
xmlTextWriter.BaseStream.Position = 0;
StreamReader sr = new StreamReader(xmlTextWriter.BaseStream);
expression = sr.ReadToEnd();
sr.Close();
}
【问题讨论】:
-
请您出示您已经在使用的代码吗? minimal reproducible example 是理想的选择。
-
如何逐行读取并添加到 StringBuilder 并稍后使用它保存在 csv 中?
标签: c# xml serialization xml-serialization