Blog

My blog serves as a way for me to post solutions to problems I solve at work or during the long hours of freelance work.


Removing Default Namespaces from an XDocument

by Ezekiel 13. September 2010 07:47

 

private static XDocument RemoveNamespace(XDocument xdoc)
{
    foreach (XElement e in xdoc.Root.DescendantsAndSelf())
    {
        if (e.Name.Namespace != XNamespace.None)
        {
            e.Name = XNamespace.None.GetName(e.Name.LocalName);
        }

        if (e.Attributes().Where(
                a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None).Any())
        {
            e.ReplaceAttributes(e.Attributes().Select(
                    a => a.IsNamespaceDeclaration ? null : a.Name.Namespace
                        != XNamespace.None ? new XAttribute(
                            XNamespace.None.GetName(a.Name.LocalName), a.Value) : a));
        }
    }

    return xdoc;
}

Tags: , , ,

C# | LINQ to XML

Convert XMLDocument to XDocument and Search for Node using C# XPath

by Ezekiel 28. July 2010 10:34

 

XmlDocument xmlDocument = method or doc load
XDocument xDocument = XDocument.Parse(xmlDocument.OuterXml);

XElement xElement = xDocument.XPathSelectElement("parentNode/childNode/subChildNode");
           
if (xElement != null)
{
    // Do some work
}

 

Tags: , , , ,

C#

RecentPosts