0

我正在尝试将多记录平面文件转换为 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>

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

<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>
4

1 回答 1

-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);

    }
于 2013-01-29T23:18:52.640 回答