System.Xml.Linq.XElement中的查询元素

时间:2019-01-08 21:07:23

标签: c#

C#代码:

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

输出:

<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>

如何扩展上面的代码以提取上面的XML输出的值“ BOB-PC”和“ 1234567”?

1 个答案:

答案 0 :(得分:0)

假设ele<HostProperties>元素的集合。您可以使用Linq to Xml来检查name属性的值,以获取元素的正确值。如果获取的是空引用,则必须添加其他的空检查-因为我不知道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}");
        }
      }

    }
}