It’s tough to work on a project that doesn’t involve XML. XML is everywhere and I kept needing to do the same things again and again from project to project. I took my C# XML utility methods, converted them to extension methods, and then put them into a class that I could drop in to my projects as needed.
Here’s a link to download these methods in a C# class file (*.cs).
public static class XmlUtilityExtensionMethods
{
///
/// Returns a list of elements that match a desired
/// name while ignoring any namespace management
/// issues.
///
/// Node to start searching from.
/// Node name that you want to retrieve.
///
public static IEnumerable
this XElement parent, string name)
{
if (parent == null)
{
return null;
}
else
{
var result = (from temp in parent.Elements()
where temp.Name.LocalName == name
select temp);
return result;
}
}
///
/// Returns the first of element that matches
/// a desired name while ignoring any
/// namespace management issues.
///
/// Node to start searching from.
/// Node name that you want to retrieve.
///
public static XElement ElementByLocalName(
this XElement parent, string name)
{
if (parent == null)
{
return null;
}
else
{
var result = (from temp in parent.Elements()
where temp.Name.LocalName == name
select temp).FirstOrDefault();
return result;
}
}
///
/// Find the first matching child element by element name
/// that has a particular attribute and attribute value.
///
/// Node to start searching from.
/// Node name that you want to retrieve.
/// Attribute to search for.
/// Desired attribute value for the search.
///
public static XElement ElementByLocalNameAndAttributeValue(
this XElement parent,
string elementName,
string attributeName,
string attributeValue)
{
var matchingElementsByName = parent.ElementsByLocalName(elementName);
var match = (from temp in matchingElementsByName
where
temp.HasAttributes == true &&
temp.AttributeValue(attributeName) == attributeValue
select temp).FirstOrDefault();
return match;
}
///
/// Finds a child element starting from parent and returns the inner text value.
///
///
///
///
public static string ElementValue(
this XElement parent, string childElement)
{
var child = parent.ElementByLocalName(childElement);
if (child == null)
{
return null;
}
else
{
return child.Value;
}
}
///
/// Gets the value of an attribute on an XElement
/// without having to worry about null reference
/// problems.
///
/// Node to start searching from
/// Attribute name.
///
/// String.Empty if the attribute does not exist.
public static string AttributeValue(
this XElement parent, string attributeName)
{
if (parent == null)
{
return String.Empty;
}
else if (parent.HasAttributes == false)
{
return String.Empty;
}
else if (parent.Attribute(attributeName) == null)
{
return String.Empty;
}
else
{
return parent.Attribute(attributeName).Value;
}
}
}
I hope that you find this useful.
-Ben