以下代码有效。我所做的就是更改 StringReader :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApp10
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(FILENAME);
XtraSerializer xtra = GetXtraSerializer(xml);
}
static XtraSerializer GetXtraSerializer(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(XtraSerializer));
StringReader reader = new StringReader(xml);
return (XtraSerializer)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "property")]
public class Property
{
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlText]
public string Text { get; set; }
[XmlElement(ElementName = "property")]
public List<Property> property { get; set; }
}
[XmlRoot(ElementName = "XtraSerializer")]
public class XtraSerializer
{
[XmlElement(ElementName = "property")]
public List<Property> Property { get; set; }
[XmlText]
public string Text { get; set; }
}
}
我为此使用了Newtonsoft。首先我转换为 json,然后转换为 c# 对象。