Reputation: 2979
I have existing xml document.
e.g
<Test>
<A />
</Test>
I load this xml into XDocument. I need to add attribute xmlns to this document and save it with this attribute.
var xml = new XDocument.Load("c:\\filePath.xml");
When I'm trying this:
xml.Root.SetAttributeValue("xmlns", "http://namespaceuri");
I'm getting exception:
System.Xml.XmlException: The prefix '' cannot be redefined from 'http://namespaceuri' to within the same start element tag.
thanks
Upvotes: 3
Views: 8031
Reputation: 1500435
You need to set the names to be in the namespace as well:
XNamespace ns = "http://namespaceuri";
foreach (var element in xml.Descendants().ToList())
{
element.Name = ns + element.Name.LocalName;
}
xml.Root.SetAttributeValue("xmlns", ns.ToString());
Basically you're trying to move all the elements to that namespace and make it the default namespace for the root element down. You can't change the default namespace while leaving the element itself in a different-but-unqualified namespace.
Using the code above with your sample XML (fixed to close A
) ends up with:
<Test xmlns="http://namespaceuri">
<A />
</Test>
Note that this code will change the namespace of all elements. If you want to be more selective, you should add a Where
call after the xml.Descendants()
call, e.g.
foreach (var element in xml.Descendants()
.Where(x => x.Name.Namespace == XNamespace.None)
.ToList())
Upvotes: 7