既然你已經提到,XML數據是從外部來源的,所以很明顯你沒有超過對照。
因此,你可以按照任何如下的選項:
- 創建每個XML數據結構不同的類,因爲據我所知是沒有辦法控制XML反序列化使用
XmlSerializer
- 您可以在使用
XDocument
自行讀取XML,克服這種限制。
如果第二個想法去,我已經創建了小控制檯應用程序來證明。
的代碼主片是如下:
MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));
XDocument doc = XDocument.Load(xmlStream);
var records = from record in doc.Descendants("item").Descendants()
select new Item(!record.IsEmpty ? record.Value : record.Attribute("value").Value);
在這裏,我使用讀取和LinqToXml檢查該元素不是空的元件,即,Value
是不是空白的,然後使用Value
否則讀元素的值爲Attribute
。
控制檯應用程序(完整代碼):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace Console.TestApp
{
class Program
{
static string xmltypeFirst = @"<item>
<name>John</name>
</item>";
static string xmltypeSecond = @"<item>
<name value='Smith' />
</item>";
static void Main(string[] args)
{
var data = xmltypeFirst;
var result = Deserialize(data).ToList();
Console.WriteLine("Name: " + result[0].Name);
data = xmltypeSecond;
result = Deserialize(data).ToList();
Console.WriteLine("Name: " + result[0].Name);
Console.WriteLine("Press any to key to exit..");
Console.ReadLine();
}
private static IEnumerable<Item> Deserialize(string xmlData)
{
MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData));
XDocument doc = XDocument.Load(xmlStream);
var records = from record in doc.Descendants("item").Descendants()
select new Item(!record.IsEmpty ? record.Value : record.Attribute("value").Value);
return records;
}
}
[Serializable]
public class Item
{
public Item(string name)
{
this.Name = name;
}
[XmlElement("name")]
public string Name { get; set; }
}
}
注意:要運行這個,你需要在你的項目中添加引用System.Xml.Linq.dll
。
參考:here
IMO這是不可能的。您將不得不完成輸入XML文件的格式。但這是一個有趣的問題。 – niksofteng