How can I find a specific node in my XML?

前端 未结 5 1741
别跟我提以往
别跟我提以往 2021-01-01 22:28

I have to read the xml node \"name\" from the following XML, but I don\'t know how to do it.

Here is the XML:



        
相关标签:
5条回答
  • 2021-01-01 23:00

    Maybe try this

    XmlNodeList nodes = root.SelectNodes("//games/game")
    foreach (XmlNode node in nodes)
    {
        listBox1.Items.Add(node["name"].InnerText);
    }
    
    0 讨论(0)
  • 2021-01-01 23:04

    Or try this:

    XmlNodeList nodes = root.GetElementsByTagName("name");
    for(int i=0; i<nodes.Count; i++)
    {
    listBox1.Items.Add(nodes[i].InnerXml);
    }
    
    0 讨论(0)
  • 2021-01-01 23:05

    Here is an example of simple function that finds and fetches two particular nodes from XML file and returns them as string array

    private static string[] ReadSettings(string settingsFile)
        {
            string[] a = new string[2];
            try
            {
                XmlTextReader xmlReader = new XmlTextReader(settingsFile);
                while (xmlReader.Read())
                {
                    switch (xmlReader.Name)
                    {
                        case "system":
                            break;
                        case "login":
                            a[0] = xmlReader.ReadString();
                            break;
                        case "password":
                            a[1] = xmlReader.ReadString();
                            break;
                    }
    
                }    
                return a;
            }
            catch (Exception ex)
            {
                return a;
            }
        }
    
    0 讨论(0)
  • 2021-01-01 23:07

    You are really close - you found the game node, why don't you go a step further and just get the name node if it exists as a child under game?

    in your for each loop:

    listBox1.Items.Add(node.SelectSingleNode("game/name").InnerText);
    
    0 讨论(0)
  • 2021-01-01 23:12
    import xml.etree.ElementTree as ET
    
    tree= ET.parse('name.xml')
    root= tree.getroot()
    
    print root[0][0].text
    
    • root = games
    • root[0] = game
    • root[0][0] = name
    • root[0][1] = url
    • use the ".text" to get string representation of value
    • this example is using python
    0 讨论(0)
提交回复
热议问题