从子类获取元素名称

时间:2019-02-02 00:33:41

标签: c# xmlserializer

从此代码生成XML时:

internal class Program
  {
    public static void Main(string[] args)
    {

      using (StreamWriter myWriter = new StreamWriter(@"C:\Users\tomas\Documents\foo.xml", false))
      {
        var myFoo = new Foo();
        myFoo.Bar = new BarChildOne();

        XmlSerializer mySerializer = new XmlSerializer(typeof(Foo));
        mySerializer.Serialize(myWriter, myFoo);
      }
    }
  }

  public class Foo
  {
    public BarBase Bar { get; set; }
  }

  [XmlInclude(typeof(BarChildOne))]
  [XmlInclude(typeof(BarChildTwo))]
  public abstract class BarBase
  {
    public string Name { get; set; }
  }

  [XmlRoot(ElementName = "BarChildOne")]
  public class BarChildOne : BarBase
  {
    public BarChildOne()
    {
      this.Name = "BarChildOne";
    }
  }

  [XmlRoot(ElementName = "BarChildTwo")]
  public class BarChildTwo : BarBase
  {
    public BarChildTwo()
    {
      this.Name = "BarChildTwo";
    }
  }

创建了这样的XML:

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Bar xsi:type="BarChildOne">
    <Name>BarChildOne</Name>
  </Bar>
</Foo>

但是,我希望元素名称为 BarChildOne ,而不是 Bar 。 >

当前:<Bar xsi:type="BarChildOne"> 预期:<BarChildOne>

如果派生类为BarChildTwo,则预期名称为<BarChildTwo>

内置XML序列化程序可以做到吗?

1 个答案:

答案 0 :(得分:0)

更新Foo中的变量名称:

public class Foo
{
    public BarBase BarChildOne { get; set; }
}

并在序列化过程中更新引用变量的名称:

using (StreamWriter myWriter = new StreamWriter(@"C:\temp\foo.xml", false))
{
    var myFoo = new Foo();
    myFoo.BarChildOne/**/ = new BarChildOne();

    XmlSerializer mySerializer = new XmlSerializer(typeof(Foo));
    mySerializer.Serialize(myWriter, myFoo);
}

产生请求的结果:

  

我希望元素名称是子类中定义的BarChildOne,而不是Bar。

<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BarChildOne xsi:type="BarChildOne">
    <Name>BarChildOne</Name>
  </BarChildOne>
</Foo>