System.Xml.Linq.XmlHelper.SetAttribute C# (CSharp) Method

SetAttribute() public method

给xPath匹配到的第一个节点追加属性. 对于该节点已存在的属性,将会覆盖这个属性的值
public SetAttribute ( string xPath, string>.IDictionary attributes ) : bool
xPath string xPath表达式
attributes string>.IDictionary 属性集合
return bool
        public bool SetAttribute(string xPath, IDictionary<string, string> attributes)
        {
            var element = GetXElement(xPath);
            if (element == null) return false;
            if (attributes == null || !attributes.Any())return false;
            foreach (var attr in attributes)
            {
                //XAttribute attribute = new XAttribute(attr.Key, attr.Value);
                //childElement.Add(attribute);
                var attribute = element.Attribute(attr.Key);
                if (attribute==null)    //表示不存在该属性
                {
                    attribute = new XAttribute(attr.Key, attr.Value);
                }
                else        //存在该属性
                {
                    attribute.Value = attr.Value;
                }
            }
            return true;
        }

Usage Example

        public XmlElement GetAuthElement()
        {
            XmlHelper h = new XmlHelper("<Authentication />");
            h.SetAttribute(".", "Extends", Type.ToString());


            if (dgRestrict.Rows.Count > 0 || dgExt.Rows.Count > 0)
                h.AddElement(".", "UserInfoProcessors");

            if (dgRestrict.Rows.Count > 0)
            {
                XmlElement xml = h.AddElement("UserInfoProcessors", "Processor");
                xml.SetAttribute("Type", "restrict");

                XmlHelper xh = new XmlHelper(xml);
                foreach (DataGridViewRow row in this.dgRestrict.Rows)
                {
                    XmlElement res = row.Tag as XmlElement;
                    xh.AddElement(".", res);
                }
            }

            foreach (DataGridViewRow row in this.dgExt.Rows)
            {
                XmlElement xml = h.AddElement("UserInfoProcessors", "Processor");
                xml.SetAttribute("Type", "ExtendProperty");

                XmlHelper xh = new XmlHelper(xml);

                XmlElement res = row.Tag as XmlElement;
                xh.AddElement(".", res);
            }

            return h.GetElement(".");
        }