我试图在下面的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");
也尝试过这个解决方案:将Linq与Xml命名空间结合使用
这里有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查询,但它们都返回Null
或no values to enumerate
。
发布于 2016-08-27 14:53:28
在这种情况下,不需要应用命名空间:
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;
发布于 2016-08-27 15:07:25
请试以下几点
XDocument document = XDocument.Load("content.xml");
var name = document.XPathSelectElement("Report/ReportHost/HostProperties/tag[@name='operating-system']").Value;
https://stackoverflow.com/questions/39182293
复制相似问题