XML序列化抑制每个类的单独节点

时间:2013-01-29 23:07:27

标签: c# xml serialization

我正在尝试将多记录平面文件转换为xml。我为每种记录类型都有一个单独的类。有些类只有一个实例,不需要用“类节点”分隔。有些人有多次出现,需要分开。使用xml序列化程序时,我无法找到有关忽略/删除类名的任何帮助。

public class Class1
{
    public string StringA;
    public string StringB;
    public string StringC;

}
public class Class2
{
    public string StringD;
    public string StringE;
    public string StringF;
}
 public class Class3
{
    public string Name;
    public Class1 User1 = new Class1 { StringA = "A String", StringB = "B String", StringC = "C String" };
    public Class2 User2 = new Class2 { StringD = "D String", StringE = "E String", StringF = "F String" };

}

这是序列化:

XmlSerializer x = new XmlSerializer(typeof(Class3));
var test = new Class3();
test.Name = "Name";
x.Serialize(Console.Out, test);

我得到以下内容:

<Class3>
<Name>Name</Name> 
<User1>
  <StringA>A String</StringA> 
  <StringB>B String</StringB> 
  <StringC>C String</StringC> 
</User1>
<User2>
  <StringD>D String</StringD> 
  <StringE>E String</StringE> 
  <StringF>F String</StringF> 
</User2>

我希望和节点消失并成为:

<Class3>
  <Name>Name</Name>
  <StringA>A String</StringA>
  <StringB>B String</StringB>
  <StringC>C String</StringC>
  <StringD>D String</StringD>
  <StringE>E String</StringE>
  <StringF>F String</StringF>
</Class3>

1 个答案:

答案 0 :(得分:-1)

最简单,最灵活的方式是实现IXmlSerializable(至少在Class3上)。

您可能需要查看此内容:http://www.codeproject.com/Articles/43237/How-to-Implement-IXmlSerializable-Correctly

public class Class3 : IXmlSerializable
{
    public string Name;
    public Class1 User1 = new Class1 
    {
        StringA = "A String",
        StringB = "B String",
        StringC = "C String"
    };

    public Class2 User2 = new Class2
    {
        StringD = "D String",
        StringE = "E String",
        StringF = "F String"
    };

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {

    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteElementString("Name", Name);
        writer.WriteElementString("StringA", User1.StringA);
        writer.WriteElementString("StringB", User1.StringB);
        writer.WriteElementString("StringC", User1.StringC);

        writer.WriteElementString("StringD", User2.StringD);
        writer.WriteElementString("StringE", User2.StringE);
        writer.WriteElementString("StringF", User2.StringF);

    }