简体   繁体   中英

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. 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:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM