How can I find a specific node in my XML?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 17:55:42

问题


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:

<?xml version="1.0" standalone="yes" ?>
  <games>
    <game>
      <name>Google Pacman</name>
      <url>http:\\www.google.de</url>
    </game>
  </games>

Code:

using System.Xml;

namespace SRCDSGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\games.xml");


            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("//games");

            foreach (XmlNode node in nodes)
            {
                listBox1.Items.Add(node["game"].InnerText);
            }


        }
    }
}

回答1:


Maybe try this

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



回答2:


Or try this:

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



回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/10033173/how-can-i-find-a-specific-node-in-my-xml

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