[英]C# Parse XML with repeated pattern of nodes
Hi I have the following xml file: 嗨,我有以下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>
How can i get the following: 我如何获得以下信息:
ONE , AAA , cBackgroundTextA 一个,AAA,cBackgroundTextA
ONE , BBB , cBackgroundTextB 一个,BBB,cBackgroundTextB
ONE , CCC , cBackgroundTextC 一个,CCC,cBackgroundTextC
TWO , DDD , cBackgroundTextD 两个,DDD,cBackgroundTextD
TWO , EEE , cBackgroundTextE 两个,EEE,cBackgroundTextE
... ...
Try something along the line: 尝试一些方法:
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}");
}
}
I finally managed to get the values by: 我终于设法通过以下方式获取值:
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
};
}
}
All required information can be gathered using single LINQ query : 可以使用单个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.