using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Benday.Utils
{
///
/// A handful of handy utility methods for working with XML
/// using XDocument, XElement, and XAttribute in C#.
///
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.
/// List of matching XElement objects.
public static IEnumerable ElementsByLocalName(
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.
/// The first matching XElement object.
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.
/// The first matching XElement object.
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.
/// The attribute value on the element or
/// 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;
}
}
}
}