2013-02-08 152 views

回答

2
List<string> items = XDocument.Parse("the xml") 
         .Descendants("item") 
         .Select(item => item.Attribute("id").Value).ToList(); 

使用XDocument!

0

,最好的辦法是解析XML。

反序列化它需要一個由XmlSerializer支持的方案,使用XDocument來解析它。

這裏是系列化的示例:

定義類

public class item 
{ 
    [XmlAttribute("item")] 
    public string id { get; set; } 
} 

序列化

var xs = new XmlSerializer(typeof(item[])); 
xs.Serialize(File.Open(@"c:\Users\roman\Desktop\ser.xml", FileMode.OpenOrCreate), new item[] { new item { id = "1" }, new item { id = "1" }, new item { id = "1" } }); 

結果:

<?xml version="1.0"?> 
<ArrayOfItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <item item="1" /> 
    <item item="1" /> 
    <item item="1" /> 
</ArrayOfItem> 

正如你可以看到它使用了一個特殊的XML架構,使你的XML無法解析,這意味着你將不得不手動分析XML,使用的XDocument或XmlDocument的,還是先使用XmlSerializer的序列化數據,然後反序列化。

3

其實,這是可能的 - 答案here顯示如何。只需將屬性定義爲數組,但用XmlElement

public class Item 
{ 
    [XmlAttribute("id")] 
    public int Id { get ;set; } 

    [XmlText] 
    public string Name { get; set; } 
} 

[XmlRoot("root")] 
public class Root 
{ 
    [XmlElement("item")] 
    public Item[] Items { get;set;} 
} 
+0

肯定答案 –