MariusD
MariusD

Reputation: 129

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!!

Upvotes: 2

Views: 401

Answers (2)

Chuck Savage
Chuck Savage

Reputation: 11945

Anytime you do pageFooter = XElement.Load(file) you are replacing anything that is in pageFooter with the contents of the file. Setting the rep namespace beforehand will have no effect on the XElement.Load().

Are you sure that the XML file has a namespace for pageFooter?

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

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;

Upvotes: 2

Related Questions