CSharp examples for System.Xml:XML Attribute
Recursive search for first matching XML node, returning attribute
using System.Xml; using System;/* ww w .j av a2 s . c om*/ public class Main{ /// <summary> /// Recursive search for first matching node, returning attribute /// </summary> /// <param name="xmlNode"></param> /// <param name="nodeName"></param> /// <param name="attributeName"></param> /// <param name="searchSiblings"></param> /// <param name="found"></param> /// <returns></returns> public static string GetAttributeValue(XmlNode xmlNode, string nodeName, string attributeName, bool searchSiblings, out bool found) { found = false; if (xmlNode == null) { return ""; } if (xmlNode.Name == nodeName) { var attribute = xmlNode.Attributes?[attributeName]; //No attribute if (attribute == null) { return ""; } found = true; return attribute.Value; } //Do any of the current nodes children have the value? var childHasValue = GetAttributeValue(xmlNode.FirstChild, nodeName, attributeName, true, out found); if (found) { return childHasValue; } if (searchSiblings) { var nextSibling = xmlNode.NextSibling; while (nextSibling != null) { var siblingAttribute = GetAttributeValue(nextSibling, nodeName, attributeName, false, out found); if (found) { return siblingAttribute; } nextSibling = nextSibling.NextSibling; } } return ""; } }