[英]Get number of subnodes for each XML root node
這就是XML的外觀。
<nvd xmlns:scap-core=....>
<entry id="CVE-2015-0001">
<vuln:vulnerable-configuration id="http://www.nist.gov/">
<cpe-lang:logical-test operator="OR" negate="false">
<cpe-lang:fact-ref name="cpe:/o:microsoft:windows_8:-"/>
<cpe-lang:fact-ref name="cpe:8.1:-"/>
<cpe-lang:fact-ref name="cpe:/o:microer_2012:-:gold"/>
<cpe-lang:fact-ref name="cpe:/o:microsoft:w~~"/>
我想獲得每個條目的“cpe-lang:fact-ref”節點的數量,並顯示條目id和節點數。
CVE-2015-0001 4
這是我試過的
var document = XDocument.Load("nvdcve-2.0-2015.xml");
var root = document.Root;
var elements = root.Descendants("entry");
foreach (var entry in elements)
{
string id = entry.Attribute("id").Value;
var cpe = entry.Elements("cpe-lang:fact-ref");
int nr = 0;
foreach (var item in cpe)
{
nr++;
}
Console.WriteLine(id + " " + nr );
}
你快到了:
var cpe = entry.Descendants("cpe-lang:fact-ref");
但實際上你不需要內循環:
foreach (var entry in elements)
{
var id = entry.Attribute("id").Value;
var factRefsCount = entry.Descendants("cpe-lang:fact-ref").Count();
Console.WriteLine(id + " " + factRefsCount);
}
改變這一行:
var elements = root.Descendants("entry");
成為:
var elements = root.Descendants()
.Where(x => x.Name.LocalName == "entry");
您在entry
節點上有一個命名空間,由於我們無法看到它,我們無法幫助您。 但是,上面會找到所有名為entry
節點。
你的專線正在尋找沒有名稱空間的節點(沒有命名空間的節點)命名entry
,而且沒有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.