I am trying to remove some attributes from xml document. Here is what I tried:
private void RemoveEmptyNamespace(XElement element) {
foreach (XElement el in element.Elements()) {
if (el.Attribute("xmlns") != null && el.Attribute("xmlns").Value == string.Empty)
el.Attribute("xmlns").Remove();
if (el.HasElements)
RemoveEmptyNamespace(el);
}
}
But it doesn't work. When I debug inside the method, attribute is removed, but when the method is fully executed, no changes were saved. The document is the same. I suppose that is because of foreach loop, but I don't see other way of looping through.
Any suggestions are appreciated.
EDIT: Here is the whole code I am using:
var file = new FileStream(destinationPath, FileMode.Open);
var doc = new XDocument();
doc = XDocument.Load(savedFile);
RemoveEmptyNamespace(doc.Root);//method above
file.SetLength(0);
doc.Save(file);
file.Close();
EDIT2: Now I have tried to achieve the same goal by going line by line and replacing strings. And nothing happens!!! The document is still the same. If somebody had similar problem, please help me.
I have found what the actual problem was. XDocument class was adding blank xmlns every time I changed something in the document! That is why I couldn't remove them. It behaves like that because it needs namespace definition for every XElement you create. So I solved the problem by doing so. The only thing that needs to be done is adding namespace to the XElement name. Something like this:
XNamespace nameSpace = "http://schemas.microsoft.com/developer/msbuild/2003";
var subType = new XElement(nameSpace + "SubType"); // strange but true
I hope this will help someone with the same problem. Thanks everybody for your answers.