How can I find a specific node in my XML?

血红的双手。 提交于 2019-11-30 12:17:17
Krishna

Maybe try this

XmlNodeList nodes = root.SelectNodes("//games/game")
foreach (XmlNode node in nodes)
{
    listBox1.Items.Add(node["name"].InnerText);
}

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

Or try this:

XmlNodeList nodes = root.GetElementsByTagName("name");
for(int i=0; i<nodes.Count; i++)
{
listBox1.Items.Add(nodes[i].InnerXml);
}

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;
        }
    }
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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!