lugeno
lugeno

Reputation: 1065

Retrieve nodes from XML belonging to a specific node

I have a XML like this:

    <ITEM>
  <RACES>
    <TAB>
      <NUMBER>1</NUMBER>
      <A></A>
      <B></B>
    </TAB>
    <TAB>
      <NUMBER>2</NUMBER>
      <A></A>
      <B></B>
    </TAB>
  </RACES>
</ITEM>

is it possible to retrieve as XmlNodeList all the As and Bs nodes that belong to only TAB with NUMBER 1?

I use the following codes, but it gives me of course 2 nodes. I want only 1 node :

XmlNodeList xnList = xml.SelectNodes("/ITEM/RACES/TAB/A");

Upvotes: 0

Views: 151

Answers (4)

touchofevil
touchofevil

Reputation: 613

You can do xmlDocument.SelectNodes(expression)

where if you need both nodes A & B

expression = @"//TAB[NUMBER=1]/A|//TAB[NUMBER=1]/B"

if you need only A node seperately

expression = @"//TAB[NUMBER=1]/A"

if you need only B node seperately

expression = @"//TAB[NUMBER=1]/B"

Upvotes: 1

Jagadeesh Govindaraj
Jagadeesh Govindaraj

Reputation: 8255

it will be return what you need

Happy coding

  var items = XElement.Parse(xmlelemet)
                        .Elements("RACES")
                        .Elements("TAB")
                        .Where(n => n.Attribute("NUMBER").Value == 1)
                        .Elements();

Upvotes: 0

Jonesopolis
Jonesopolis

Reputation: 25370

I strongly recommend Linq to Xml. You can knock it out in one statement:

var nodes_A_and_B = XDocument.Parse(xml)
                     .Descendants("TAB")
                     .Where(t => t.Element("NUMBER").Value == "1")
                     .Select(t => new 
                             {
                                A = t.Element("A"), 
                                B = t.Element("B")
                             }); 

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Try as below:

XmlNodeList xnList = xml.SelectNodes("/RACES/TAB");
foreach (XmlNode xn in xnList)
{
  int num = xn["NUMBER"].InnerText;
  if(num==1)
  {
    Console.WriteLine("Nodes: {0} {1}", xn["A"], xn["B"]);
  }
}

Upvotes: 0

Related Questions