将 XML 元素反序列化为字符串

本文关键字:字符串 反序列化 元素 XML | 更新日期: 2024-11-08 03:10:36

>我有这个 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>

和这个类

[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; }
}

我正在使用以下代码来反序列化 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);
        }

这里的问题是,我希望内容元素中的 xml 内容被反序列化为字符串。这可能吗?

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

将 XML 元素反序列化为字符串

怀疑有没有反序列化的方法...对于 Linq to XML,它看起来像这样:

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()
                }
            });
    }
}

编辑

如果您也想剥离内容标记:

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()))
                }
            });
    }
}
相关文章: