user641490
user641490

Reputation: 51

Get specific data from XML document

I have xml document like this:

<level1>
 <level2>
  <level3>
   <attribute1>...</attribute1>
   <attribute2>false</attribute2>
   <attribute3>...</attribute3>
  </level3>
  <level3>
   <attribute1>...</attribute1>
   <attribute2>true</attribute2>
   <attribute3>...</attribute3>
  </level3>
</level2>
<level2>
 <level3>
   <attribute1>...</attribute1>
   <attribute2>false</attribute2>
...
...
...

I'm using c#, and I want to go thru all "level3", and for every "level3", i want to read attribute2, and if it says "true", i want to print the corresponding attribute3 (can be "level3" without these attributes).

I keep the xml in XmlDocument. Then I keep all the "level3" nodes like this:

XmlNodeList xnList = document.SelectNodes(String.Format("/level1/level2/level3"));

(document is the XmlDocument).

But from now on, I don't know exactly how to continue. I tried going thru xnList with for..each, but nothing works fine for me..

How can I do it?

Thanks a lot

Upvotes: 1

Views: 1550

Answers (3)

Elian Ebbing
Elian Ebbing

Reputation: 19057

You can use an XPath query. This will give you a XmlNodeList that contains all <attribute3> elements that match your requirement:

var list = document.SelectNodes("//level3[attribute2 = 'true']/attribute3");

foreach(XmlNode node in list)
{
    Console.WriteLine(node.InnerText);
}

You can split the above xpath query in three parts:

  1. "//level3" queries for all descendant elements named <level3>.
  2. "[attribute2 = 'true']" filters the result from (1) and only keeps the elements where the child element <attribute2> contains the text true.
  3. "/attribute3" takes the <attribute3> childnode of each element in the result of (2).

Upvotes: 0

Josef Pfleger
Josef Pfleger

Reputation: 74557

You can use LINQ to XML and reading this is a good start.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503290

Well I'd use LINQ to XML:

var results = from level3 in doc.Descendants("level3")
              where (bool) level3.Element("attribute2")
              select level3.Element("attribute3").Value;

foreach (string result in results)
{
    Console.WriteLine(result);
}

LINQ to XML makes all kinds of things much simpler than the XmlDocument API. Of course, the downside is that it requires .NET 3.5...

(By the way, naming elements attributeN is a bit confusing... one would expect attribute to refer to an actual XML attribute...)

Upvotes: 4

Related Questions