Situation
I'm using XDocument
to try and remove an xmlns=""
attribute on the first inner node:
<Root xmlns="http://my.namespace">
<Firstelement xmlns="">
<RestOfTheDocument />
</Firstelement>
</Root>
So what I want as a result is:
<Root xmlns="http://my.namespace">
<Firstelement>
<RestOfTheDocument />
</Firstelement>
</Root>
Code
doc = XDocument.Load(XmlReader.Create(inStream));
XElement inner = doc.XPathSelectElement("/*/*[1]");
if (inner != null)
{
inner.Attribute("xmlns").Remove();
}
MemoryStream outStream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(outStream);
doc.Save(writer); // <--- Exception occurs here
Problem
Upon trying to save the document, I get the following exception:
The prefix '' cannot be redefined from '' to 'http://my.namespace' within the same start element tag.
What does this even mean and what can I do to remove that pesky xmlns=""
?
Notes
- I do want to keep the root node's namespace
- I only want that specific
xmlns
removed, there will be no other xmlns
attributes in the document.
Update
I've tried using code inspired from answers on this question:
inner = new XElement(inner.Name.LocalName, inner.Elements());
When debugging, the xmlns
attribute is gone from it but I get the same exception.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…