开发者

C# - Array from XML as an embedded resource

开发者 https://www.devze.com 2023-04-02 10:27 出处:网络
I\'ve been trying to find a good clean way to load the contents of an XML file into an array to use but I\'ve only found partial answers here and there. My XML file is an Embedded Resource for simplic

I've been trying to find a good clean way to load the contents of an XML file into an array to use but I've only found partial answers here and there. My XML file is an Embedded Resource for simplicity, and contains a list of about 115 elements that all contain an id and name attribute.

The XML looks like so:

<?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>

I'm able to load everything in and I see my data in the InnerXML but I cannot find out how to access it correctly.

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();  
          开发者_如何学Go      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));
        }
    }

That's the code I have that would ideally set this array up for me to use, though it is fairly broken due to me trying different things, but I think it conveys the general idea. Hopefully someone can make some sense of it and explain to me what I'm doing horribly wrong (>.<) I would be happy to provide more information, clarification, etc if I missed something important!

Thanks!


Using 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();


Use an xpath.

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

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

精彩评论

暂无评论...
验证码 换一张
取 消