Deserialize element value as string although it contains mixed content

前端 未结 2 1788
野趣味
野趣味 2021-01-13 05:29

Assuming an XML like this:


    content
    
            


        
2条回答
  •  逝去的感伤
    2021-01-13 06:10

    This isn't quite finished because I can't remember if you can / how to add the namespace prefix to the root element in Xml Serialization. But if you implement the IXmlSerializable interface in your MyRoot class like this:

    [XmlRoot("Root", Namespace="http://foo/bar")]
    public class MyRoot : IXmlSerializable
    

    Then write the XML serialization methods yourself, something like this:

            void IXmlSerializable.ReadXml(System.Xml.XmlReader reader)
            {
                reader.MoveToContent();
                var outerXml = reader.ReadOuterXml();
                XElement root = XElement.Parse(outerXml);
    
                this.FieldBasic = root.Elements(XName.Get("FieldBasic", "http://foo/bar")).First().Value;
                this.FieldComplex = root.Elements(XName.Get("FieldComplex", "http://foo/bar")).First().Elements().First().Value.Trim();
            }
    
    
    
            void IXmlSerializable.WriteXml(System.Xml.XmlWriter writer)
            {
                writer.WriteRaw(String.Format("\r\n\t\r\n\t\t{0}\r\n\t", this.FieldBasic));
                writer.WriteRaw(String.Format("\r\n\t\r\n\t\t{0}\r\n\t\r\n", this.FieldComplex));
            }
    

    (Return null from the GetSchema method)

    This should get you at least pretty close to what you're after.

    You may also find these links helpful.

    IXmlSerializable

    Namespaces

提交回复
热议问题