我有这个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>
答案 0 :(得分:0)
怀疑反序列化的方法......使用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()))
}
});
}
}