I have an XML file formatted like this:
testcode1
&l
This is extension to answers above, if your xml has namespace defined (xmlns
) then you will get a nasty side effect when adding children - xmlns = ""
being added to your new child element.
What you want to do (assuming element you are adding belongs to same namespace as his parent) is to take namespace from parent element parentElement.GetDefaultNamespace()
.
var child = new XElement(parentElement.GetDefaultNamespace()+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));
child.Add(new XAttribute("Attr3", "777"));
parentElement.Add(child);
for parent elements with multiple namespaces you can choose which one to use by changing from parentElement.GetDefaultNamespace()+"Snippet"
to parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet"
e.g
var child = new XElement(parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));