How to get an XML node value as string when deserializing

主宰稳场 提交于 2019-12-02 04:39:29

You can deserialize arbitrary, free-form XML data using XmlSerializer by marking target properties with [XmlAnyElement].

E.g. you can define your Addenda type as follows:

[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    public Addenda Addenda { get; set; }
}

public class Addenda
{
    [XmlAnyElement]
    [XmlText]
    public XmlNode[] Nodes { get; set; }
}

Sample working .Net fiddle #1.

Or, you could eliminate the Addenda type completely and replace it with an XmlElement property in the containing type:

[XmlRoot("Comprobante", Namespace = "http://cfdi")]
public class Comprobante : IValidatableObject
{
    [Required]
    [XmlArray("Conceptos"), XmlArrayItem(typeof(Concepto), ElementName = "Concepto")]
    public List<Concepto> Conceptos { get; set; }

    [XmlAnyElement("Addenda")]
    public XmlElement Addenda { get; set; }
}

Sample working .Net fiddle #2.

Notes:

  • When applied without an element name, [XmlAnyElement] specifies that the member is an array of XmlElement or XmlNode objects which will contain all arbitrary XML data that is not bound to some other member in the containing type.

  • When applied with an element name (and optional namespace), [XmlAnyElement("Addenda")] specifies that the member is a either a single XmlElement object or an array of such objects, and will contain all arbitrary XML elements named <Addenda>. Using this form eliminates the need for the extra Addenda type.

  • Combining [XmlText] with [XmlAnyElement] allows arbitrary mixed content to be deserialized.

  • If you are using .NET Core you may need to nuget System.Xml.XmlDocument.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!