读取每个特定节点的所有XML子节点 [英] Read all XML child nodes of each specific node
问题描述
我需要读取我的<Imovel>
标记的所有Child Nodes
,问题是我的XML文件中有多个(一个)<Imovel>
标记,并且每个<Imovel>
标记之间的区别是一个名为ID的属性.
I need to read all the Child Nodes
of my <Imovel>
tag, the problem is that I has more than 1 (one) <Imovel>
tag in my XML file, and the difference between each <Imovel>
tag is an attribute called ID.
这是一个示例
<Imoveis>
<Imovel id="555">
<DateImovel>2012-01-01 00:00:00.000</DateImovel>
<Pictures>
<Picture>
<Path>hhhhh</Path>
</Picture>
</Pictures>
// Here comes a lot of another tags
</Imovel>
<Imovel id="777">
<DateImovel>2012-01-01 00:00:00.000</DateImovel>
<Pictures>
<Picture>
<Path>tttt</Path>
</Picture>
</Pictures>
// Here comes a lot of another tags
</Imovel>
</Imoveis>
我需要读取每个<Imovel>
标记的所有标记,并且在我在<Imovel>
标记中进行的每个验证的最后,我需要执行另一个验证.
I need read all tags of each <Imovel>
tag, and in the end of each validation that I do in my <Imovel>
tag I need to do another validation.
所以,我想我需要做2个(两个)foreach
或for
和foreach
,我对LINQ
不太了解,但是请遵循我的示例
So, I think I need to do 2 (two) foreach
or a for
and a foreach
, I don't understand very well about LINQ
but follow my sample
XmlReader rdr = XmlReader.Create(file);
XDocument doc2 = XDocument.Load(rdr);
ValidaCampos valida = new ValidaCampos();
//// Here I Count the number of `<Imovel>` tags exist in my XML File
for (int i = 1; i <= doc2.Root.Descendants().Where(x => x.Name == "Imovel").Count(); i++)
{
//// Get the ID attribute that exist in my `<Imovel>` tag
id = doc2.Root.Descendants().ElementAt(0).Attribute("id").Value;
foreach (var element in doc2.Root.Descendants().Where(x => x.Parent.Attribute("id").Value == id))
{
String name = element.Name.LocalName;
String value = element.Value;
}
}
但是在我的foreach
语句中效果不佳,因为我的<Picture>
标记及其父标记没有ID属性.
But doesn't work very well, in my foreach
statement because my <Picture>
tag, her parent tag don't has an ID attribute.
有人可以帮我做这种方法吗?
Somebody can help me to do this method ?
推荐答案
您应该可以使用两个foreach语句来做到这一点:
You should be able to do this with two foreach statements:
foreach(var imovel in doc2.Root.Descendants("Imovel"))
{
//Do something with the Imovel node
foreach(var children in imovel.Descendants())
{
//Do something with the child nodes of Imovel.
}
}
这篇关于读取每个特定节点的所有XML子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!