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);
}
}
}
}
Maybe try this
XmlNodeList nodes = root.SelectNodes("//games/game")
foreach (XmlNode node in nodes)
{
listBox1.Items.Add(node["name"].InnerText);
}
Or try this:
XmlNodeList nodes = root.GetElementsByTagName("name");
for(int i=0; i<nodes.Count; i++)
{
listBox1.Items.Add(nodes[i].InnerXml);
}
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);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.