我正在将一个类序列化为XML文档,并且我想了解如何向该类的多个字段添加自定义属性。我知道我们可以用 [XMLAttribute(AttributeName =“ CustomAttribute”]将自定义属性添加到XML文档的单个节点,但是我不知道如何向多个节点添加自定义属性。
我的课如下:
[XmlRoot(ElementName = "customer")]
public class Customer
{
[XmlElement(ElementName = "cust_id")]
public string CustomerId {get; set;}
[XmlElement(ElementName = "cust_name")]
public string CustomerName {get; set; }
[XmlElement(ElementName = "cust_phone")]
public string CustomerPhone {get; set; }
[XmlElement(ElementName = "cust_email")]
public string CustomerEmail {get; set; }
}
而且,我正在使用以下代码将类序列化为XML:
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using (var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
序列化上面的类后,我得到以下XML:
<customer>
<cust_id>1</cust_id>
<cust_name>John</cust_name>
<cust_phone>12345678</cust_phone>
<cust_email>john@gmail.com</cust_email>
</customer>
现在,如果客户类的任何字段为null,我想将相应的XML节点标记为IsNull =“ TRUE”。例如:
<customer>
<cust_id>1</cust_id>
<cust_name>John</cust_name>
<cust_phone IsNull = "TRUE" />
<cust_email IsNull = "TRUE" />
</customer>
我们如何像上面那样将一个类序列化为XML,以便为XML文档的多个节点设置自定义属性?
谢谢