Add XML Attribute Namespace Safe - CSharp System.Xml

CSharp examples for System.Xml:XML Attribute

Description

Add XML Attribute Namespace Safe

Demo Code


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  .  c  om

public class Main{
        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;
        }
        public static XName RemoveNamespace(this XName self)
        {
            return XName.Get(self.LocalName);
        }
        public static string ToXmlValue(this object self)
        {
            return Convert.ToString((self ?? String.Empty), CultureInfo.InvariantCulture);
        }
}

Related Tutorials