[英]C# XML Read All Child Nodes Of A Specific Node
So I have a program that reads all the name nodes in a XML file and adds these to a Combo Box. 因此,我有一个程序可以读取XML文件中的所有名称节点,并将其添加到组合框。 On a button click, it then takes this response and needs to get all the other data from the child nodes of the node the name is in. 单击按钮后,它会采取此响应,并需要从名称所在节点的子节点中获取所有其他数据。
The XML document: XML文件:
<People>
<Person>
<Name>Greg</Name>
<Age>23</Age>
<Height>200</Height>
</Person>
<Person>
<Name>John</Name>
<Age>34</Age>
<Height>230</Height>
</Person>
</People>
What I've got so far: 到目前为止,我得到的是:
XmlDocument Doc = new XmlDocument();
Doc.Load(FilePath);
foreach (XmlNode Node in Doc.SelectNodes("People/Person"))
{
comboBox1.Items.Add(Node.SelectSingleNode("Name").InnerText);
}
string RegPicked = comboBox1.SelectedItem.ToString();
foreach (XmlNode xNode in Doc.SelectNodes("People/Person"))
if (xNode.SelectSingleNode("Name").InnerText == RegPicked)
{
textBox1.Text = xNode.ParentNode.ChildNodes.ToString();
}
Doc.Save(FilePath);
When I run the code I just get "System.Xml.XmlChildNodes" in the text box. 运行代码时,我仅在文本框中获得“ System.Xml.XmlChildNodes”。 I know I've done something wrong but I'm not sure what. 我知道我做错了什么,但不确定。
您必须区分子节点:
textBox1.Text = xNode.ParentNode.ChildNodes.SelectSingleNode("age").InnerText;
Do this, you will get all the elements inside the parent of the node you are searching the value of. 这样做,您将获得要搜索其值的节点的父级内的所有元素。
string str = @"<People>
<Person>
<Name>Greg</Name>
<Age>23</Age>
<Height>200</Height>
</Person>
<Person>
<Name>John</Name>
<Age>34</Age>
<Height>230</Height>
</Person>
</People>";
XDocument xdoc = XDocument.Parse(str);
var xmlURL = (from el in xdoc.Descendants("Name")
where el.Value == "John"
select el.Parent).First().ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.