Xml序列化属性和文本

时间:2010-10-21 19:15:07

标签: .net-3.5 xml-serialization

我有一个我需要重新创建的简单Xml节点

<Division ID="123">Division Name</Division> 

但是当我创建类

public class Division
{
    [XmlAttribute]
    public string Id { get; set; }

    [XmlText]
    public string Description { get; set; }
}

我得到了

<Division>Division Name</Division> 

Id消失了。

我该如何做到这一点?

1 个答案:

答案 0 :(得分:1)

Works on my machine


Division d = new Division()
{
    Id = "1",
    Description = "Description"
};

FileStream fs = new FileStream("test.txt", FileMode.Create);
TextWriter writer = new StreamWriter(fs, new UTF8Encoding());


XmlSerializer xs = new XmlSerializer(typeof(Division));
xs.Serialize(writer, d);
writer.Close();

<?xml version="1.0" encoding="utf-8"?>
<Division xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
       xmlns:xsd="http://www.w3.org/2001/XMLSchema" Id="1">Description</Division>