[英]C# Parse XML with repeated pattern of nodes
嗨,我有以下xml文件:
<?xml version="1.0" encoding="utf-8"?>
<Resources>
<Category Cause="ONE">
<Resource Component="AAA" Name="cBackgroundTextA" />
<Resource Component="BBB" Name="cBackgroundTextB" />
<Resource Component="CCC" Name="cBackgroundTextC" />
</Category>
<Category Cause="TWO">
<Resource Component="DDD" Name="cBackgroundTextD" />
<Resource Component="EEE" Name="cBackgroundTextE" />
<Resource Component="FFF" Name="cBackgroundTextF" />
</Category>
<Category Cause="THREE">
<Resource Component="GGG" Name="cBackgroundTextG" />
<Resource Component="HHH" Name="cBackgroundTextH" />
<Resource Component="III" Name="cBackgroundTextI" />
</Category>
</Resources>
我如何獲得以下信息:
一個,AAA,cBackgroundTextA
一個,BBB,cBackgroundTextB
一個,CCC,cBackgroundTextC
兩個,DDD,cBackgroundTextD
兩個,EEE,cBackgroundTextE
...
嘗試一些方法:
XElement root;
foreach(var folder in root.Children()) { //For each folder
var folderType = folder.Attribute("type").Value;
foreach(var file in folder.Children()) { //For each file
Console.WriteLine($"{folderType} AND {file}");
}
}
我終於設法通過以下方式獲取值:
xmlDocument = new XDocument();
xmlDocument = XDocument.Load(filePath, LoadOptions.None);
var categoryNodeList = XmlDocument.Descendants("Category");
foreach (XElement categoryItem in categoryNodeList)
{
foreach (XElement resourceItem in categoryItem.Elements())
{
var XmlObject = new ResultDetail
{
Cause = categoryItem.Attribute("Cause").Value,
Component = resourceItem.Attribute("Component").Value,
Name = resourceItem.Attribute("Name").Value
};
}
}
可以使用單個LINQ查詢來收集所有必需的信息:
var query = from cat in XmlDocument.Descendants("Category");
from res in cat.Elements()
select new ResultDetail
{
Cause = cat.Attribute("Cause").Value,
Component = res.Attribute("Component").Value,
Name = res.Attribute("Name").Value
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.