Reputation: 4740
How can I select a specific node in my XML
file ?
In my first foreach
I select every Property
that are inside my Properties
tag, but I want a specific Property
. A Property
that has the <PropertyCode>
equals 123 for example.
XML
<Carga>
<Properties>
<Property>
<PropertyCode>122</PropertyCode>
<Fotos>
<Foto>
</Foto>
</Fotos>
</Property>
<Property>
<PropertyCode>123</PropertyCode>
<Fotos>
<Foto>
</Foto>
</Fotos>
</Property>
</Properties>
</Carga>
C# Code
// Here I get all Property tag
// But i want to take just a specific one
foreach (XmlElement property in xmldoc.SelectNodes("/Carga/Properties/Property"))
{
foreach (XmlElement photo in imovel.SelectNodes("Fotos/Foto"))
{
string photoName = photo.ChildNodes.Item(0).InnerText.Trim();
string url = photo.ChildNodes.Item(1).InnerText.Trim();
this.DownloadImages(property_id, url, photoName );
}
}
Someone can help me?
Upvotes: 1
Views: 505
Reputation: 15265
You can use a predicate expression in your XPath to pick out specific nodes.. something like this:
XmlNodeList nl = xmldoc.SelectNodes("/Carga/Properties/Property[PropertyCode='123']/Fotos/Foto");
foreach(XmlNode n in nl) { ... }
See here for a quick reference to XPath syntax: http://www.w3schools.com/xpath/xpath_syntax.asp
Upvotes: 1
Reputation: 236218
Use Linq to Xml:
int code = 123;
var xdoc = XDocument.Load(path_to_xml);
var property = xdoc.Descendants("Property")
.FirstOrDefault(p => (int)p.Element("PropertyCode") == code);
if (property != null)
{
var fotos = property.Element("Fotos").Elements().Select(f => (string)f);
}
fotos
will be collection of strings.
Upvotes: 3