我想要获取当前Photo
标记xml中的所有Property
标记。
XML
<Properties>
<Property>
<Photos>
<Photo>
</Photo>
</Photos>
</Property>
<Property>
<Photos>
<Photo>
</Photo>
</Photos>
</Property>
<Property>
<Photos>
<Photo>
</Photo>
</Photos>
</Property>
</Properties>
代码
xmlnode = xmldoc.GetElementsByTagName("Property");
for (int i = 0; i < xmlnode.Count - 1; i++)
{
XmlNodeList xmlNode2;
xmlNode2 = xmldoc.GetElementsByTagName("Photo");
// I wanna get all the Photo tag that are inside the current Property tag
for (int j = 0; j < xmlNode2.Count - 1; j++)
{
// Get the total of tags called Photo in my XML
}
}
但在我的代码中,我在所有Photos
文件中获得XML
标记的总数,而不是当前Property
标记。
我该怎么做?
答案 0 :(得分:1)
请注意,选择所有Property
元素的代码与获取Photo
元素的代码相同。
使用索引,您可以依靠XPath来处理XML文档,如下所示:
// Starting XPath expression with a slash means: "starting at document element"
foreach (XmlElement property in xmldoc.SelectNodes("/Properties/Property"))
{
Console.WriteLine("Property");
// Without a starting slash, you'll use current node context
foreach (XmlElement photo in property.SelectNodes("Photos/Photo"))
{
Console.WriteLine("\tPhoto");
}
}
输出:
Property
Photo
Property
Photo
Property
Photo
答案 1 :(得分:0)
using System.Linq;
using System.Xml.Linq;
public void ProcessPhotos() {
XDocument xDoc = XDocument.Load("<path to your xml file");
foreach(XElement xProperty in xDoc.Descendants("Property")) {
// goes through all Property xml elements
foreach(XElement xPhoto in xProperty.Descendants("Photo")) {
// and process all photos in current Property element
}
}
}