2011-09-02 57 views
1

我一直在试图找到一个好的干净的方式来加载一个XML文件的内容到一个数组来使用,但我只找到部分答案在这里和那里。为简单起见,我的XML文件是嵌入式资源,其中包含大约115个元素的列表,这些元素都包含idname属性。C# - 从XML作为嵌入式资源的数组

的XML看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Item> 
     <id>1</id> 
     <name>Example1</name> 
    </Item> 
    <Item> 
     <id>2</id> 
     <name>Example2</name> 
    </Item> 
    <Item> 
     <id>3</id> 
     <name>Example3</name> 
    </Item> 
</Items> 

我能够在加载的一切,我看到在我的InnerXML数据,但我不能找出如何正确地访问它。

public Form1() 
    { 
     InitializeComponent(); 

     assembly = Assembly.GetExecutingAssembly(); 
     XmlDocument xml = null; 
     try 
     { 
      string filePath = "MyProject.ItemList.xml"; 
      Stream fileStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filePath); 
      if (fileStream != null) 
      { 
       xml = new XmlDocument(); 
       xml.Load(fileStream); 
      } 
     } 
     catch { 
      //Do nothing 
     } 

     XmlDocument itemsFromXML = xml.DocumentElement.InnerXml; 

     foreach (XmlNode node in itemsFromXML) 
     { 
      int id = Convert.ToInt32(node.Attributes.GetNamedItem("id").ToString()); 
      string name = node.Attributes.GetNamedItem("name").ToString(); 

      gameItemList.Add(new GameItem(id, name)); 
     } 
    } 

这是我有一个理想的情况设置该阵列为我用的代码,但它是相当坏由于我尝试不同的东西,但我认为它传达的总体思路。希望有人能够对此有所了解,并向我解释我做错了什么(>。<)如果我错过了一些重要的事情,我会很乐意提供更多信息,澄清等等。

谢谢!

回答

1

使用xpath。

XmlNodeList nodes = xml.SelectNodes("Items/Item"); 

foreach (XmlNode node in nodes) 
{ 
    int id = int.Parse(node.SelectSingleNode("id").InnerText); 
} 
+0

真棒,谢谢你的快速反应,工作就像一个魅力。 –

3

使用System.Xml.Linq的:

var items = XElement.Load(fileStream) 
       .Elements("Item") 
       .Select(itemXml => new { 
        id = (int)itemXml.Element("id").Value, 
        name = itemXml.Element("name").Value 
       }) 
       .ToArray();