[英]Read all XML child nodes of each specific node
我需要閱讀我的<Imovel>
標簽的所有Child Nodes
,問題是我的XML文件中有超過1(一)個<Imovel>
標簽,每個<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>
我需要讀取每個<Imovel>
標簽的所有標簽,並且在我的<Imovel>
標簽中進行的每次驗證結束時,我需要進行另一次驗證。
所以,我認為我需要做2(2) foreach
或者for
和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;
}
}
但由於我的<Picture>
標簽,她的父標簽沒有ID屬性,因此在我的foreach
語句中效果不佳。
有人可以幫我做這個方法嗎?
您應該能夠使用兩個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.
}
}
試試這個。 System.Xml.XPath將xpath選擇器添加到XElement。 使用xpath查找元素更快更簡單。
您不需要XmlReader和XDocument來加載文件。
XElement root = XElement.Load("test.xml");
foreach (XElement imovel in root.XPathSelectElements("//Imovel"))
{
foreach (var children in imovel.Descendants())
{
String name = children.Name.LocalName;
String value = children.Value;
Console.WriteLine("Name:{0}, Value:{1}", name, value);
}
//use relative xpath to find a child element
XElement picturePath = imovel.XPathSelectElement(".//Pictures/Picture/Path");
Console.WriteLine("Picture Path:{0}", picturePath.Value);
}
請包括
System.Xml.XPath;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.