C# - XML - Treat inner xml from a certain element as string

后端 未结 1 1496
灰色年华
灰色年华 2021-01-14 02:09

I have the following XML:


0
1

  06098INF17613         


        
1条回答
  •  有刺的猬
    2021-01-14 02:44

    XmlText expects a text node, but what you have are actually element nodes. I don't know if there's a direct way to do that, but you can have a XmlAnyElement node to collect the result of the deserialization, and afterwards you merge them in a single string if that's what you need, as shown in the example below.

        [XmlRoot("Plan")]
        public class EPlan
        {
            [XmlElement("Error")]
            public string Error { get; set; }
    
            [XmlElement("Description")]
            public string Description { get; set; }
    
            [XmlElement("Document")]
            public List Documents { get; set; }
        }
    
        [XmlType]
        public class EDocument
        {
            private string document;
    
            [XmlAnyElement]
            [EditorBrowsable(EditorBrowsableState.Never)]
            public XmlElement[] DocumentNodes { get; set; }
    
            [XmlIgnore]
            public string Document
            {
                get
                {
                    if (this.document == null)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (var node in this.DocumentNodes)
                        {
                            sb.Append(node.OuterXml);
                        }
    
                        this.document = sb.ToString();
                    }
    
                    return this.document;
                }
            }
        }
    
        static void Test()
        {
            string xml = @"
      0
      1
      
        06098INF1761320
        109340336
        DAVID STEVENSON
        
        
        
      
      
        id2
        ced2
        abstract2
        
        
        
      
    ";
            XmlSerializer xs = new XmlSerializer(typeof(EPlan));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));
            EPlan obj = xs.Deserialize(ms) as EPlan;
            Console.WriteLine(obj.Documents[0].Document);
        }
    

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