Retrieve nodes from XML belonging to a specific node

≡放荡痞女 提交于 2019-12-13 07:59:33

问题


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");

回答1:


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"



回答2:


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"]);
  }
}



回答3:


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")
                             }); 



回答4:


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


来源:https://stackoverflow.com/questions/30125027/retrieve-nodes-from-xml-belonging-to-a-specific-node

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!