【发布时间】:2016-08-27 14:37:39
【问题描述】:
我正在尝试在下面的 xml 代码中获取 operating-system 属性的值,但在我尝试过的所有解决方案中,从堆栈、dotnetcurry 和 Microsoft 至今,我都得到了 NullPointerExecption 或它只是不返回任何值。
这是我要解析的 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");
也试过这个解决方案:Use Linq to Xml with Xml namespaces
我在 Microsoft 教程中有这个方法,但它只返回 true/false,我无法对其进行操作,以便将值 Microsoft Windows 7 Enterprise Service Pack 1 分配给 os 变量。
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",
};
我尝试过使用上面的where 子句使用各种其他Linq-to-Xml 查询,但它们都返回Null 或no values to enumerate。
【问题讨论】:
-
顺便说一句——这个问题的提出真的很好。提供相关数据以进行尝试,您没有得到什么以及您尝试过的内容:)随着时间的推移得到改善:)
标签: c# xml linq linq-to-xml xml-namespaces