简体   繁体   中英

How to retrieve tags inside certain tag for XML using GetElementsByTagName/SelectNode/SelectSingleNode?

Let say I have a XML with this format:

<TEST>
    <DRINK>
        <NAME>Ice tea</NAME>
        <NAME>Milo</NAME>
        <NAME>Coffee</NAME>
    </DRINK>
    <FOOD>
        <NAME>Fried Rice</NAME>
        <NAME>Hamburger</NAME>
        <NAME>Fried Noodles</NAME>
    </FOOD>
</TEST>

How to retrieve only food names and put them in the ASP.NET web form textbox?

This is my current code:

XmlDocument doc = new XmlDocument();
doc.Load(filepath);
root = doc.DocumentElement;
TextBox1.Text = root.GetElementsByTagName("NAME")[0].InnerText;
TextBox2.Text = root.GetElementsByTagName("NAME")[1].InnerText;
TextBox3.Text = root.GetElementsByTagName("NAME")[2].InnerText;

This code will instead retrieve drink names instead of food names. How to make it read NAME tags in FOOD tag?

By using XmlNode.SelectNodes Method with providing the XPath.

var foodElements = root.SelectNodes("FOOD/NAME");

Console.WriteLine(foodElement[0].InnerText);
Console.WriteLine(foodElement[1].InnerText);
Console.WriteLine(foodElement[2].InnerText);

Sample .NET Fiddle

Basic xml parsing.

this:

    {
        string sXML
            =
          @"<TEST>
                <DRINK>
                    <NAME>Ice tea</NAME >   
                    <NAME>Milo</NAME >   
                    <NAME>Coffee</NAME> 
                </DRINK>   
                <FOOD>
                    <NAME>Fried Rice</NAME>      
                    <NAME>Hamburger</NAME>
                    <NAME>Fried Noodles</NAME>         
                </FOOD>
            </TEST>";


        XmlDocument myXml = new XmlDocument();
        myXml.LoadXml(sXML);

        XmlNodeList myNodes = myXml.SelectNodes("TEST/FOOD/NAME");

        foreach (XmlNode OneNode in myNodes)
        {
            Debug.Print(OneNode.InnerText);
        }
    }

output: 在此处输入图像描述

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