简体   繁体   中英

Query elements in System.Xml.Linq.XElement

C# code:

List<XElement> ele = reportHost.hostProperties.ToList();          
foreach (var item in ele)
{
 Console.WriteLine("XML: {0}", item);
}

OUTPUT:

<HostProperties>
  <tag name="cpe">cpe:/o:linux:linux_kernel</tag>
  <tag name="device">1234567</tag>
  <tag name="FQN">BOB-PC</tag>
  <tag name="Domain">Internal</tag>
 </HostProperties>

How can I expand the code above to extract the values "BOB-PC" and "1234567" for the XML output above?

Assuming ele is a collection of <HostProperties> elements. You can use Linq to Xml to check the value of the name attribute to get the correct values of the element. If you are getting null references, you will have to add additional null checks - as I don't know what is required or not in the xml.

List<XElement> hostProperties = reportHost.hostProperties.ToList(); 

// iterate through each <hostProperties> element
foreach (var hp in hostProperties)
{
    // all of the <tag> elements
    var tags = hp.Element("HostProperties").Elements("tag");

    foreach (var tag in tags)
    {
      // get the attribute with the name of "name"
      var tagName = tag.Attribute("name");

      // check to make sure a <tag> element exists with a "name" attribute
      if (tagName != null)
      {
        if (tagName.Value == "device")
        {
          Console.WriteLine($"device: {tag.Value}");
        }
        else if (tagName.Value == "fqn")
        {
          Console.WriteLine($"fqn: {tag.Value}");
        }
      }

    }
}

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