如何使用XmlElement注释设置序列化类的XML值



我有一个这样写的类:

[XmlRoot]
public class MyXMLElement
{
    [XmlAttribute]
    public string AnAttribute { get; set; }
    [XmlAttribute]
    public string AnotherElementAttribute { get; set; }
}

当this被序列化时,我想设置它的值,所以我得到如下内容:

<MyXMLElement AnAttribute="something" AnotherElementAttribute="something else">The inner value of the element</MyXMLElement>

有人有什么想法吗?

如果您想设置元素的值,您可以使用[XmlText]属性:

[XmlRoot]
public class MyXMLElement
{
    [XmlAttribute]
    public string AnAttribute { get; set; }
    [XmlAttribute]
    public string AnotherElementAttribute { get; set; }
    [XmlText]
    public string Value { get; set; }
}

添加另一个属性来保存内部文本,并使用XmlTextAttribute

标记它
[XmlRoot]
public class MyXMLElement
{
    [XmlAttribute]
    public string AnAttribute { get; set; }
    [XmlAttribute]
    public string AnotherElementAttribute { get; set; }
    [XmlText]
    public string InnerText { get; set; }
}

如果您编写自己的序列化器(示例如下),可以很容易地做到这一点。这也可以让你完全控制你的对象是如何持久化的,而不是依赖于。net决定怎么做。

interface IXmlConvertable{
    XElement ToXml();

}

public class MyClass : IXmlConvertable{
    public string Name { get; set; }
    public string ID { get; set; }
    public XElement ToXml(){
        var retval = new XElement("MyClass"
            , new XAttribute("Name", new XCData(Name))
            , new XAttribute("ID", new XCData(ID))
            );
        return retval;
    }
}

最新更新