XML 解析方法(1)

  public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null)
        {
            var foundEl = parentEl.Element(elementName);
            if (foundEl != null)
            {
                return foundEl.Value;
            }
            else
            {
                return defaultValue;
  public static string TryGetElementAttribute(this XElement element, string attributeName, string defaultValue = null)
        {           
                var foundAttr = element.Attribute(attributeName);
                if (foundAttr != null)
                    return foundAttr.Value;
                else
                    return defaultValue;
          
        }

        public static string TryGetElementAttribute(this XElement parentEl, string elementName, string attributeName, string defaultValue = null)
        {
            var foundEl = parentEl.Element(elementName);
            if (foundEl != null)
            {
                var foundAttr = foundEl.Attribute(attributeName);
                if (foundAttr != null)
                    return foundAttr.Value;
                else
                    return defaultValue;
            }
            else
            {
                return defaultValue;
            }
        }

        public static string TryGetElementValueByAttribute(this XElement parentEl, string elementName, string attributeName, string defaultValue = null)
        {
            string retVal = defaultValue;
            if (parentEl.HasElements) {
                foreach (var element in parentEl.Descendants()) {
                   
                    var foundAttr = element.Attribute("name");
                    if (foundAttr != null && foundAttr.Value == attributeName)
                    {
                        retVal = element.Value;
                        break;                        
                    }                       
                }
            }
            return retVal;
            
        }  

            }
          }
做个快乐的自己。
原文地址:https://www.cnblogs.com/Jessy/p/2320861.html