简体   繁体   English

Xml序列化添加具有属性的元素

[英]Xml serialization add element with properties

I have two classes: 我有两节课:

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

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

It serializes into xml like this: 它像这样序列化为xml:

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

I would like to specify element name in Content and gets something like this 我想在Content中指定元素名称并得到类似的东西

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

Can i do this without creating new class witch will contains B using standart xml serialization? 我是否可以在不创建新类的情况下执行此操作,将使用标准xml序列化包含B?

One option you have is to declare the SomeName property in class A as a collection of objects of type B and then make use of the [XmlArray] and [XmlArrayItem] attributes. 你有一个选择是将申报SomeName类属性A类型的对象的集合B再利用的[XmlArray][XmlArrayItem]属性。

Here is a working example. 这是一个有效的例子。 Be aware that I changed the property SomeName to SomeNames . 请注意,我将属性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);
}

The result produced by this example will be as desired by you: 此示例生成的结果将符合您的要求:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM