如何在XML中找到特定节点?
我必须从以下XML中读取xml节点“name”,但我不知道该怎么做。
这是XML:
Google Pacman http:\\www.google.de
码:
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); } } } }
也许试试这个
XmlNodeList nodes = root.SelectNodes("//games/game") foreach (XmlNode node in nodes) { listBox1.Items.Add(node["name"].InnerText); }
你真的很接近 – 你找到了游戏节点,你为什么不更进一步,如果它作为一个孩子在游戏中存在,只是得到名称节点?
在你的每个循环中:
listBox1.Items.Add(node.SelectSingleNode("game/name").InnerText);
下面是一个简单函数示例,它从XML文件中查找并获取两个特定节点,并将它们作为字符串数组返回
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; } }
或试试这个:
XmlNodeList nodes = root.GetElementsByTagName("name"); for(int i=0; i
import xml.etree.ElementTree as ET tree= ET.parse('name.xml') root= tree.getroot() print root[0][0].text
- root =游戏
- root [0] =游戏
- root [0] [0] =名称
- root [0] [1] = url
- 使用“.text”来获取值的字符串表示
- 这个例子是使用python