access xml element by attribute value
hoipolloi has given an XPath answer, which is fine - but I would personally use LINQ to XML. (See my blog post on code and data for reasons.)
var element = parent.Descendants()
.Where(x => (Guid?) x.Attribute("id") == id)
.FirstOrDefault();
This will perform appropriate GUID parsing on each id
attribute (returning a "null" Guid?
value for non-GUIDs). If you're certain of the text format of your ID, you can cast to string instead:
var element = parent.Descendants()
.Where(x => (string) x.Attribute("id") == idText)
.FirstOrDefault();
Change the FirstOrDefault
to Single
, SingleOrDefault
or First
depending on your requirements.
EDIT: It's not at all clear what's going wrong with the code you've posted. Here's a short but complete program which shows it working fine. Please compare this with your code:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = "<parent><foo id='bar' /><foo id='baz' /></parent>";
XDocument doc = XDocument.Parse(xml);
string idToFind = "bar";
XElement selectedElement = doc.Descendants()
.Where(x => (string) x.Attribute("id") == idToFind).FirstOrDefault();
Console.WriteLine(selectedElement);
}
}
You can use XPath to do this. For instance, the following matches all elements with an id of 'foo', irrespective of their location in the document:
//*[@id='foo']