我用这个:
[http://xmltocsharp.azurewebsites.net/][1]
从某些XML创建一些类。有时翻译建议:
[XmlElement(ElementName="sup")]
public List<string> Sup { get; set; }
有时:
[XmlElement(ElementName = "sup")]
public Sup Sup { get; set; } }
我可以使我的反序列化类更强大以应对两种情况吗?
PS:
使用此:
[XmlElement(ElementName= "sub")]
public List<Sub> Sub { get; set; }
[XmlElement(ElementName = "sup")]
public List<Sup> Sup { get; set; }
使一切变得更强大
答案 0 :(得分:1)
请参阅我为您创建的示例,这两个XML都将使用给定的模型进行处理
仅使用对象列表的所有父项 如果我们仍在获取字符串,那么它将仍然需要,并且如果该对象的单个对象或多个对象的字符串列表也相同,那么所有问题都将得到解决
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Hello</heading>
<heading>Hello2</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Tove</to>
<from>Jani</from>
<heading><subhead>Data</subhead></heading>
<body>Don't forget me this weekend!</body>
</note>
[XmlRoot(ElementName = "note")]
public class Note
{
[XmlElement(ElementName = "to")]
public string To { get; set; }
[XmlElement(ElementName = "from")]
public string From { get; set; }
[XmlElement(ElementName = "heading")]
public List<object> Heading { get; set; }
[XmlElement(ElementName = "body")]
public string Body { get; set; }
}
整个测试示例:-
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://pleasecheckXML.txt");
XmlSerializer xmldata = new XmlSerializer(typeof(Note));
byte[] byteArray = Encoding.ASCII.GetBytes(data);
MemoryStream stream = new MemoryStream(byteArray);
var datafromxml = xmldata.Deserialize(stream);
}
}
[XmlRoot(ElementName = "note")]
public class Note
{
[XmlElement(ElementName = "to")]
public string To { get; set; }
[XmlElement(ElementName = "from")]
public string From { get; set; }
[XmlElement(ElementName = "heading")]
public List<object> Heading { get; set; }
[XmlElement(ElementName = "body")]
public string Body { get; set; }
}
}