Search code examples
c#xml

deserialize xml element as string


I have this xml

<Report Name="Report">
  <Input>
    <Content>
      <XmlInput>Any xml inside the input tag should be deserialised as string</XmlInput>
      <XmlInput>Any xml inside the input tag should be deserialised as string</XmlInput>
    </Content>
    <!--<XmlInput>Any xml inside the input tag should be deserialised as string</XmlInput>-->
  </Input>
</Report>

and this class

[XmlRoot("Report")]
public class  Report
{
    [XmlAttribute]
    public string Name { get; set; }

    public Input Input { get; set; }
}

public class Input
{
    [XmlElement]
    public string Content { get; set; }
}

I am using the following code to deserialize the xml

        string path = @"C:\temp\myxml.xml";
        var xmlSerializer = new XmlSerializer(typeof(Report));
        using (var reader = new StreamReader(path))
        {
            var report = (Report)xmlSerializer.Deserialize(reader);
        }

The problem here is, I want the xml content inside the content element to be deserialized as a string. Is this possible?

 <Content>
  <XmlInput>Any xml inside the input tag should be deserialised as string</XmlInput>
  <XmlInput>Any xml inside the input tag should be deserialised as string</XmlInput>
</Content>

Solution

  • Doubt there's a way with deserialization... With Linq to XML it would look like this:

    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("XMLFile1.xml");
    
            IEnumerable<XElement> reportElements = doc.Descendants("Report");
    
            IEnumerable<Report> reports = reportElements
                .Select(e => new Report 
                { 
                    Name = e.Attribute("Name").Value,
                    Input = new Input
                    {
                        Content = e.Element("Input").Element("Content").ToString()
                    }
                });
        }
    }
    

    Edit

    If you want to strip the content tag too:

    class Program
    {
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load("XMLFile1.xml");
    
            IEnumerable<XElement> reportElements = doc.Descendants("Report");
    
            IEnumerable<Report> reports = reportElements
                .Select(e => new Report
                {
                    Name = e.Attribute("Name").Value,
                    Input = new Input
                    {
                        Content = string.Join("\n", e.Element("Input").Element("Content").Elements().Select(c => c.ToString()))
                    }
                });
        }
    }