Recent Posts

Thursday, July 31, 2008

XML with C#/.NET 2.0 and XPathNavigator

I had a bit tricky kind of xml shown as follows:

data
customer
id1/id
fullname John Smith /fullname
/customer
custaddress
streetname 100 George St /streetname
suburb Sydney /suburb
/custaddress
customer
id 2 /id
fullname Paul Smith /fullname
/customer
customer
id 3 /id
fullname Mary Smith /fullname
/customer
custaddress
streetname 100 George St /streetname
suburb Sydney /suburb
/custaddress
/data

(Note: I have removed "<" and ">" in the xml data because this blogger is giving me funny results while posting i don't want to go through it now)


Here customerAddress lies outside the customer tag and it exists only to those cutomers who has address.
Now to find which customer is related to what address it was a bit of a trick so I posted my query in msdn forum and found the following answer which worked quiet well for me

Guys facing the same or similar problems can solve this in the following way:

foreach (XPathNavigator customer in new XPathDocument(@"..\..\XMLFile1.xml").CreateNavigator().Select("data/Customer"))
{
Console.WriteLine("Id: {0}, full name: {1}", customer.SelectSingleNode("ID").Value, customer.SelectSingleNode("FullName").Value);
XPathNavigator address = customer.SelectSingleNode("following-sibling::*[1][self::CustAddress]");
if (address != null)
{
Console.WriteLine("Address: {0}, {1}", address.SelectSingleNode("StreetName").Value, address.SelectSingleNode("Suburb").Value);
}
else
{
Console.WriteLine("No address found.");
}
Console.WriteLine();
}

Related Posts by Categories




No comments:

Post a Comment