-1

How to read a tag inside another xml tag?

Example:

<site id = "1" clas = "black"><test> Value </test></site>

I want to read the test tag inside <site>. I want to return what's inside it.

My code:

XmlReader xmlReader = XmlReader.Create("site.xml");
while (xmlReader.Read())
{
    if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "site"))
    {
        if (xmlReader.HasAttributes)
        {
            string test = xmlReader.GetAttribute("id");
            Console.WriteLine(test);
        }
    }
}
Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
  • Any reason you can't just load the whole XML file into memory, say with LINQ to XML? Is the real file huge? – dbc Nov 23 '19 at 18:34
  • You can use ReadToDescendant to move to the next child element if you want to keep using XmlReader – Pawel Nov 23 '19 at 18:39
  • Assuming you need to stick with `XmlReader` this looks more or less like a duplicate of [Read Mulitple childs and extract data xmlReader in c#](https://stackoverflow.com/a/38425483/3744182), agree? – dbc Nov 23 '19 at 19:02
  • the codes are correct but i wanted to read the attribute too, my code already ***has the attribute*** but i wanted to know how to use an option to read both, some idea? – Victor Stanford Nov 24 '19 at 17:53

2 Answers2

0

You should use the System.Xml.Linq.XElement API:

using (Stream s = File.OpenRead("sites.xml")) {
    XElement sites = XElement.Load(s);
    foreach (XElement test in sites.Elements()) {
    // test is now your inner node
    }
}

If you wat to stick to XmlReader, you can use ReadSubTree(). See this example.

AZWN
  • 158
  • 12
0

you can use XMLNodeList like below

var doc = new XmlDocument();
doc.Load(sites.xml);
XmlDocument xml = new XmlDocument();
xml.LoadXml(doc.DocumentElement.OuterXml.ToString());
XmlNodeList xnList = xml.SelectNodes("/site/test");
 foreach (XmlNode xn in xnList)
            {
                if (xn["name"].InnerText == "test")
                {
                  string  testvalue = xn["test"].InnerText;
                }
            }
Usman Asif
  • 320
  • 2
  • 12