A possible solution would be to use LINQ2XML:
// retrieve a single element by tag name
private XElement getElement(XDocument xmlDocument, string elementName)
{
var element = xmlDocument.Descendants("items").Elements().Where (x => x.Name == elementName).FirstOrDefault();
return element != null ? element : null;
}
// retrieve attribute by name
private string attributeValue(XElement item, string attributeName)
{
var attribute = item.Attribute(attributeName);
return attribute != null ? attribute.Value : string.Empty;
}
The two functions can be used like this:
// input for the example
var input = @"<items>
<item1 value=""value1"" />
<item2 value=""value2"" />
<item3 value=""value3"" />
<itme4 value=""value4"" />
<item5 value=""value5"" />
<item6 value=""value6"" />
</items>";
var xml = XDocument.Parse(input);
var element = getElement(xml, "item2");
if (element != null)
{
Console.WriteLine(attributeValue(element, "value"));
}
The output is:
value2
For a repetative tasks like this it is often advantageous to implement the methods as extensions:
public static class ProjectExtensions
{
// retrieve a single element by tag name
public static XElement GetElementByName(this XDocument xmlDocument, string parentElementName, string elementName)
{
var element = xmlDocument.Descendants(parentElementName).Elements().Where (x => x.Name == elementName).FirstOrDefault();
return element != null ? element : null;
}
// retrieve attribute by name
public static string GetAttributeValueByName(this XElement item, string attributeName)
{
var attribute = item.Attribute(attributeName);
return attribute != null ? attribute.Value : string.Empty;
}
}
The usage is IMO much more easier and cleaner:
var xml = XDocument.Parse(input);
var element = xml.GetElementByName("items", "item2");
if (element != null)
{
Console.WriteLine(element.GetAttributeValueByName("value"));
}
You can of course (as already suggested) use XPath directly.
itmeand notitemas your code has them.