Deserialize element value as string although it contains mixed content

前端 未结 2 1789
野趣味
野趣味 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<my:FieldBasic>\r\n\t\t{0}\r\n\t</my:FieldBasic>", this.FieldBasic));
                writer.WriteRaw(String.Format("\r\n\t<my:FieldComplex>\r\n\t\t{0}\r\n\t</my:FieldComplex>\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

    0 讨论(0)
  • 2021-01-13 06:32

    You could use CDATA in the XML to indicate that the contents is a string literal:

    <my:Root xmlns:my="http://foo/bar">
      <my:FieldBasic>content</my:FieldBasic>
      <my:FieldComplex>
        <![CDATA[
          <html xml:space="preserve" xmlns="http://www.w3.org/1999/xhtml">
            <div><h1>content</h1></div>
          </html>
        ]]>
      </my:FieldComplex>
    </my:Root>
    
    0 讨论(0)
提交回复
热议问题