【问题标题】:Xml serialization add element with propertiesxml序列化添加元素的属性
【发布时间】:2019-06-18 08:13:01
【问题描述】:

我有两个班级:

public class A
{
    [XmlElement("Content")]
    public B SomeName { get; set; }
}

public class B
{
    [XmlAttribute]
    public int X { get; set; }
}

它像这样序列化成xml:

<A>
  <Content X="5" />
</A>

我想在 Content 中指定元素名称并得到类似的东西

<A>
  <Content>
      <Some element X="5" />
  </Content>
</A>

我可以在不创建新类的情况下使用标准 xml 序列化包含 B 吗?

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    您可以选择将SomeName 类中的SomeName 属性声明为B 类型的对象集合,然后使用[XmlArray] 和[XmlArrayItem] 属性。

    这是一个工作示例。请注意,我将属性 SomeName 更改为 SomeNames。

    [Serializable]
    public class A
    {
        [XmlArray("Content")]
        [XmlArrayItem("Some")]
        public List<B> SomeNames { get; set; } = new List<B>();
    }
    
    public class B
    {
        [XmlAttribute(AttributeName = "element")]
        public int X { get; set; }
    }
    
    public static void XmlSerialize()
    {
        var a = new A {SomeNames = new List<B> {new B() {X = 5}}};
        var serializer = new XmlSerializer(typeof(A));
        var settings = new XmlWriterSettings() {Indent = true};
        using var stream = XmlWriter.Create("serialized.xml", settings);
        serializer.Serialize(stream, a);
    }
    

    此示例产生的结果将如您所愿:

    <?xml version="1.0" encoding="utf-8"?>
    <A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Content>
        <Some element="5" />
      </Content>
    </A>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 2013-01-28
      相关资源
      最近更新 更多