我应该使用什么类型的类来生成这个Xml结构? (C#)

时间:2015-05-11 08:42:25

标签: c# xml xml-serialization

我需要创建一个模型,将序列化为此形式的Xml(这是更大的Xml的一部分):

<ManufacturerPartNumbers>
    <ManufacturerPartNumber>26-12345-8W</ManufacturerPartNumber>
    <ManufacturerPartNumber>26-12345-8Y</ManufacturerPartNumber>
    <ManufacturerPartNumber>26-12345-8Z</ManufacturerPartNumber>
</ManufacturerPartNumbers>

我尝试过使用

[XmlType(TypeName = "ManufacturerPartNumber")]
public class ManufacturerPartNumberModel
{
    public string Number { get; set; }
}

在上层阶级:

public List<ManufacturerPartNumberModel> ManufacturerPartNumbers { get; set; }

但这会产生一个额外的Xml节点:

<ManufacturerPartNumbers>
    <ManufacturerPartNumber>
      <Number>26-12345-8W</Number>
    </ManufacturerPartNumber>
</ManufacturerPartNumbers>

1 个答案:

答案 0 :(得分:1)

5分钟后我找到答案:)

我只需要将[XmlTextAttribute]添加到Number属性,它会将其序列化为ManufacturerPartNumberModel

中的无名内联属性
[XmlType(TypeName = "ManufacturerPartNumber")]
    public class ManufacturerPartNumberModel
    {
        [XmlTextAttribute]
        public string Number { get; set; }
    }