C# 如何在我的 XML 中找到特定节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10033173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I find a specific node in my XML?
提问by Jan W
I have to read the xml node "name" from the following XML, but I don't know how to do it.
我必须从以下 XML 中读取 xml 节点“名称”,但我不知道该怎么做。
Here is the XML:
这是 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);
}
}
}
}
采纳答案by Krishna
Maybe try this
也许试试这个
XmlNodeList nodes = root.SelectNodes("//games/game")
foreach (XmlNode node in nodes)
{
listBox1.Items.Add(node["name"].InnerText);
}
回答by Ryan Bennett
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);
回答by Tony
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][0] = 名称
- 根 [0][1] = 网址
- 使用“.text”获取值的字符串表示
- 这个例子使用的是python
回答by IgorM
Here is an example of simple function that finds and fetches two particular nodes from XML file and returns them as string array
这是一个简单函数的示例,该函数从 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;
}
}
回答by hx_9009
Or try this:
或者试试这个:
XmlNodeList nodes = root.GetElementsByTagName("name");
for(int i=0; i<nodes.Count; i++)
{
listBox1.Items.Add(nodes[i].InnerXml);
}

