0

I am having serious trouble adding an XElement after loading that inherits the parent's namespace... I've tried multiple examples, set the exact same namespaces in both documents, tried removing the namespaces... this is honestly a mess, the only example I found was re-creating the XElement object with a namespace in the constructor but my XML is pretty massive. I do not wish to do this. Is there a way to Inherit namespaces after a load then add to parent (see code for example of what I mean).

xml = XDocument.Load(rdlFile);
var selectNode = xml.AssumeISelectedTheNodeIWantWithLinq();
//A static element loaded from a separate file
XElement elementNeedsNameSpace = XElement.Load("element.xml");
selectNode.Add(elementNeedsNameSpace );

//Output xml:
<MyAddedNode xmlns="">
  <AssumeLotsOfChilds>
    <SubChilds/>
  </AssumeLotsOfChilds>
</MyAddedNode>

//Root xml
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">

If I remove the attribute then I get all the children messed up and receive the stupid xlmns="" :(

2
  • Try to define XNamespace 'ns = "..";' and add it with element 'selectNode.Add(ns + element);' Commented Jun 10, 2016 at 16:27
  • I like using following : xml.Descendants().Where(x => x.Name.LocalName == "AssumeLotsOfChilds"). No namespace is required. Commented Jun 10, 2016 at 19:17

1 Answer 1

1

Your 'element loaded from a separate file' and children don't have a namespace, hence the addition of xmlns="" when they're inserted into a document that has a different default namespace.

If you want to get rid of that attribute then you need to change all the element names to use the default namespace of the document you are inserting it into:

XNamespace ns = "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"

foreach (var element in elementNeedsNamespace.DescendantsAndSelf())
{
     element.Name = ns + element.Name.LocalName;
}

selectNode.Add(elementNeedsNameSpace);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.