我需要阅读所有的Child Nodes我的<Imovel>标签,问题是,我有超过1(一)<Imovel>在我的XML文件中的标记,每个之间的区别<Imovel>标签是所谓的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>
Run Code Online (Sandbox Code Playgroud)
我需要阅读每个标签的所有<Imovel>标签,并且在我在<Imovel>标签中进行的每次验证结束时,我需要进行另一次验证.
所以,我认为我需要做2(2)foreach或a for和a foreach,我不太了解LINQ但是按照我的样本
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是在我的foreach陈述中效果不好,因为我的<Picture>标签,她的父标签没有ID属性.
有人可以帮我做这个方法吗?
您应该能够使用两个foreach语句执行此操作:
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.
}
}
Run Code Online (Sandbox Code Playgroud)