[英]How to set the XML value of serialized class using the XmlElement annotation
我有一個以以下方式編寫的課程:
[XmlRoot]
public class MyXMLElement
{
[XmlAttribute]
public string AnAttribute { get; set; }
[XmlAttribute]
public string AnotherElementAttribute { get; set; }
}
序列化后,我想設置它的值,所以我得到如下信息:
<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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.