C#按属性名称获取Xelement属性值

克里斯

我试图operating-system在下面的xml代码中获取attribute的值,但是在到目前为止我尝试过的所有解决方案中,无论是堆栈,dotnetcurry和Microsoft,我都得到aNullPointerExecption或它不返回任何值。

这是我要解析的xml数据:

<Report name="Black Workstation" xmlns:cm="http://www.nessus.org/cm">
  <ReportHost name="192.168.1.000>
    <HostProperties>
        <tag name="HOST_END">Wed Jun 29 10:32:54 2016</tag>
        <tag name="LastAuthenticatedResults">1467214374</tag>
        <tag name="patch-summary-total-cves">5</tag>
        <tag name="cpe">cpe:/o:microsoft:windows</tag>
        <tag name="operating-system">Microsoft Windows 7 Enterprise Service Pack 1</tag>
    </HostProperties>
  </ReportHost>
</Report>

我已经尝试了许多方法,但是这里是最后两个:

XNamespace ns = "http://www.nessus.org/cm";
var operatingSystem = (findings.Where(a => a.Attribute("name").Value == "operating-system")
.Select(a => a.Value));                                        

var operatingSystem = findings.Descendants().Where(x => x.Attribute("name").Value == ns + "operating-system");

还尝试了此解决方案:将Linq应用于具有Xml名称空间的Xml

我在Microsoft教程中有此方法,但是它仅返回true / false,并且无法对其进行操作,以至于它将值分配Microsoft Windows 7 Enterprise Service Pack 1os变量。

XElement xelement = XElement.Load(s);
IEnumerable<XElement> findings = xelement.Elements();

var hostProperties = from hp in findings.Descendants("HostProperties")
                     select new
                     {
                         os = (string)hp.Element("tag").Attribute("name").Value == "operating-system",
                     };

我已经尝试将其他各种Linq-to-Xml查询与上述where子句一起使用,但它们都返回Nullno values to enumerate

吉拉德·格林(Gilad Green)

在您的情况下,您无需应用名称空间:

var result = XDocument.Load("data.xml")
                      .Descendants("tag")
                      .Where(e => e.Attribute("name").Value == "operating-system")
                      .FirstOrDefault()?.Value;

 //result = Microsoft Windows 7 Enterprise Service Pack 1

读多一点到它在这里你可以看到,即使你在你的XML没有定义命名空间的元素你使用它。您定义的名称空间(xmlns:cm)仅适用于带有cm:前缀的元素,并且不是其中的一个。

看看我是否按以下方式更改了您的xml(命名空间仅用于xmlns而不是xmlns:cm):

<Report name="Black Workstation" xmlns="http://www.nessus.org/cm"> 
  <ReportHost name="192.168.1.000">
  <HostProperties>
    <tag name="HOST_END">Wed Jun 29 10:32:54 2016</tag>
    <tag name="LastAuthenticatedResults">1467214374</tag>
    <tag name="patch-summary-total-cves">5</tag>
    <tag name="cpe">cpe:/o:microsoft:windows</tag>
    <tag name="operating-system">Microsoft Windows 7 Enterprise Service Pack 1</tag>
  </HostProperties>
</ReportHost>
</Report>

上面的代码将返回null,您将必须像这样编写:

XNamespace ns = "http://www.nessus.org/cm";
var result = XDocument.Load("data.xml")
                      .Descendants(ns + "tag")
                      .Where(e => e.Attribute("name").Value == "operating-system")
                      .FirstOrDefault()?.Value;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章