Reputation: 345
I do not know how to iterate through an XML document to find a node value that belongs to an item that has a specific value in another node. Let me explain more clearly...
Here is my XML:
<Items>
<Item>
<Id>id 1</Id>
<Item>item 1</Item>
<LastModified>2016-01-01</LastModified>
</Item>
<Item>
<Id>id 2</Id>
<Item>item 2</Item>
<LastModified>2016-02-02</LastModified>
</Item>
</Item>
I would like to find the value of <LastModified>
where <Id>
= id 2 so that I would get the following date: 2016-02-02.
A solution in C# using XDocument would be most appreciated.
Thanks in advance!
Upvotes: 0
Views: 461
Reputation: 26213
You need to find the Item
element that contains the Id
with your value, and then get its LastModified
element:
var lastModified = (DateTime) doc.Descendants("Item")
.Where(x => (string) x.Element("Id") == "id 2")
.Elements("LastModified")
.Single();
See this fiddle for a working example.
Upvotes: 1