Search code examples
c#xmlnamespacesxelement

how do I avoid getting the empty namespace in newly created XElement?


I am trying to delete then add a pageFooter to an xml document from a different file:

XNamespace rep = "http://developer.cognos.com/schemas/report/8.0/";

//remove pageFooter
doc.Root.Descendants().Where(e=>e.Name == rep + "pageFooter").Remove();

//create and load pagefooter from file
XElement pageFooter = XElement.Load(@"C:\pageFooter.xml");

and I am getting the empty namespace:

<pageFooter xmlns="">
    <contents>
         ..............

I tried all of the following to add the namespace to the new element, nothing works:

XElement pagefooter = new XElement(rep+"pageFooter"); 
pageFooter = XElement.Load(@"C:\pageFooter.xml");        
//this has no effect

pageFooter.Name = rep.GetName(pageFooter.Name.LocalName);
//this moves the xmlns="" to the next descendant, <contents>

pageFooter.Add(rep);   
//this has no effect

pageFooter.SetAttributeValue("xmlns", rep);
//this results an empty pageFooter

Any ideas? Thanks!!


Solution

  • You were on the right track with your second effort listed. The moving of xmlns="" to the next descendant means that pageFooter had the right xmlns, but the rest of its descendants didn't. Use this:

    foreach (var d in pagefooter.DescendantsAndSelf())
        d.Name = rep + d.Name.LocalName;