c#-从XML填充类对象
作者:互联网
我在XML下方给类填充问题,我知道如何从XML(反序列化)填充类对象,但是在XML下方对我来说是棘手的.
<Header>
<To EmailType="Personal">abc@abc.com</To>
<From EmailType="Work">abc2@abc.com</From>
</Header>
如果我在下面的类中创建,它将仅填充XML的数据部分而不填充属性,
[XmlRoot(ElementName = "Header")]
public class Header
{
public Header()
{
}
[XmlElement(ElementName = "To", Form = XmlSchemaForm.Unqualified)]
public string To { get; set; }
[XmlElement(ElementName = "From", Form = XmlSchemaForm.Unqualified)]
public string From { get; set; }
}
我希望能够解析&保存两个属性&数据.
解决方法:
我假设您想要将其反序列化为类似以下内容:
public string ToAddress {get;set;}
public EmailType ToEmailType {get;set;} // an enum
public string FromAddress {get;set;}
public EmailType FromEmailType {get;set;}
不幸的是,使用XmlSerializer是不可能的.您将必须具有一个层次模型:
public EmailDetails To {get;set;}
public EmailDetails From {get;set;}
...
public class EmailDetails {
[XmlAttribute]
public EmailType EmailType {get;set;}
[XmlText]
public string Address {get;set;}
}
或者,您将必须通过XElement或类似方法手动解析它.
标签:deserialization,xml,c 来源: https://codeday.me/bug/20191121/2052403.html