我需要将c#对象序列化为xml,我可以像格式化部分中那样进行操作,但是我们可以在没有缩进/多余空格/换行的格式化情况下实现它。这是必需的,因为我们需要将整个对象写到一个csv中,因此我们需要一个缩小的版本。我尝试了几个XmlWriterSettings,但是没有按预期工作。任何代码片段都将提供很大的帮助,要序列化的对象可以具有其他引用类型,这些成员可以从其他基类继承,因此序列化器可能需要已知的类型
格式化的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();
}
不介意,我没有将正确的对象传递给序列化器,以下工作
Type[] _knownExpressions = new Type[]
{
typeof(SimpleExpression),
typeof(CompositeExpression)
};
string expression = string.Empty;
Expression exp = new Expression(){
// Fill the object
};
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, exp);
xmlTextWriter.Flush();
xmlTextWriter.BaseStream.Position = 0;
StreamReader sr = new StreamReader(xmlTextWriter.BaseStream);
expression = sr.ReadToEnd();
sr.Close();
}