简体   繁体   中英

How do I select all of the nodes in an xml file between two tags, depending on attribute name of the tag?

I want to select all of the nodes in between the group tags where it has the name I want but I am unsure of how to do this. Below is an example where I would want to select every node where the group has the name "DefaultSettings".

<group name="DefaultSettings">
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
</group>

<group name="NewSettings">
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
    <tag></tag>
</group>

I am currently trying to use the XmlDocument object to select all of the nodes but I am unsure of how to get Xpath to work properly as I don't want to select the other group with the name NewSettings. Any advice on what Xpath formula to use or any other way would be appreicated.

Edit: I have solved this by a combination of using freeformatter.com/xpath-tester.html and just general messing around. Sorry that I didn't research it as much as I thought I did but XPath is pretty confusing and now I know a lot more about how to use it.

Assuming this is your XML

<groups>
   <group name="DefaultSettings">
      <tag />
      <tag />
      <tag />
      <tag />
      <tag />
      <tag />
   </group>
   <group name="NewSettings">
      <tag />
      <tag />
      <tag />
      <tag />
      <tag />
      <tag />
   </group>
</groups>

You can try something like this:

XmlDocument xml = new XmlDocument();
xml.LoadXml(str);  // suppose that str string contains "<groups>...</groups>"

XmlNodeList xnList = xml.SelectNodes("/groups/group[@name='DefaultSettings']");
foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

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