簡體   English   中英

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

[英]Query elements in System.Xml.Linq.XElement

C#代碼:

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>

如何擴展上面的代碼以提取上面的XML輸出的值“ BOB-PC”和“ 1234567”?

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

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM