CSharp examples for System.Xml:XML Element
Creates and returns the attribute with the given name in the location specified by the given location string in the given XML element.
using System.Linq; using System.Text; using System.Collections.Generic; using System.Globalization; using System.Xml.Linq; using System;/*from w w w. j a v a 2s . co m*/ public class Main{ /// <summary> /// Creates and returns the attribute with the given name in the location /// specified by the given location string in the given XML element. /// </summary> /// <param name="baseElement">The XML element.</param> /// <param name="location">The location string.</param> /// <param name="attrName">Name of the attribute.</param> /// <param name="attrValue">The value to be assigned to the attribute.</param> /// <returns>returns the attribute with the given name in the location /// specified by the given location string in the given XML element.</returns> public static XAttribute CreateAttribute(XElement baseElement, string location, XName attrName, object attrValue, XNamespace documentDefaultNamespace) { XElement newLoc = FindLocation(baseElement, location); if (newLoc == null) { if (CanCreateLocation(baseElement, location)) { newLoc = CreateLocation(baseElement, location); } else { return null; } } // check if the attribute does not exist if (attrName.Namespace.IsEmpty() && attrName.Namespace != documentDefaultNamespace) { // i.e., the attribute already exists if (newLoc.Attribute(attrName) != null) return null; // we cannot create another one with the same name } else { if (newLoc.Attribute_NamespaceNeutral(attrName) != null) // i.e., the attribute already exists return null; // we cannot create another one with the same name } return newLoc.AddAttributeNamespaceSafe(attrName, attrValue, documentDefaultNamespace); } public static XAttribute Attribute_NamespaceNeutral(this XElement parent, XName name) { return parent.Attributes().FirstOrDefault(e => e.Name.LocalName == name.LocalName); } public static bool IsEmpty(this XNamespace self) { return self != null && !String.IsNullOrEmpty(self.NamespaceName.Trim()); } public static XAttribute AddAttributeNamespaceSafe(this XElement parent, XName attrName, object attrValue, XNamespace documentDefaultNamespace) { var newAttrName = attrName; if (newAttrName.Namespace == documentDefaultNamespace) newAttrName = newAttrName.RemoveNamespace(); var newAttr = new XAttribute(newAttrName, attrValue.ToXmlValue()); parent.Add(newAttr); return newAttr; } }