How to get an XML node value as string when deserializing

后端 未结 1 1377
梦如初夏
梦如初夏 2021-01-23 16:44

I am sending a XML to a aspnet core web api. The value for the namespace prefix cfdi: is defined in a containing node:


           


        
1条回答
  •  有刺的猬
    2021-01-23 16:51

    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 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 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 . 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.

    0 讨论(0)
提交回复
热议问题