从XElement中删除属性

Val*_*ale 3 c# xelement

我试图从xml文档中删除一些属性.这是我尝试过的:

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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

但它不起作用.当我在方法内部调试时,属性被删除,但是当方法完全执行时,没有保存任何更改.文件是一样的.我想这是因为foreach循环,但我没有看到其他循环方式.

任何建议表示赞赏.

编辑:这是我正在使用的整个代码:

        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();
Run Code Online (Sandbox Code Playgroud)

编辑2:现在我试图通过逐行和替换字符串来实现相同的目标.什么都没发生!该文件仍然是相同的.如果有人有类似的问题,请帮助我.

Val*_*ale 9

我发现了实际问题是什么.每次我在文档中更改内容时,XDocument类都添加了空白的xmlns!这就是为什么我无法删除它们.它的行为与此类似,因为它需要为您创建的每个XElement定义命名空间.所以我通过这样做解决了这个问题.唯一需要做的是将名称空间添加到XElement名称.像这样的东西:

XNamespace nameSpace = "http://schemas.microsoft.com/developer/msbuild/2003";
var subType = new XElement(nameSpace + "SubType"); // strange but true
Run Code Online (Sandbox Code Playgroud)

我希望这能帮助有同样问题的人.谢谢大家的回答.


Ale*_*cka 6

这项工作对我来说:

private static void RemoveEmptyNamespace(XElement element)
{
    XAttribute attr = element.Attribute("xmlns");
    if (attr != null && string.IsNullOrEmpty(attr.Value))
        attr.Remove();
    foreach (XElement el in element.Elements())
        RemoveEmptyNamespace(el);
}
Run Code Online (Sandbox Code Playgroud)

唯一不同的是,我也在计算根元素中的xmlns属性.但它确实有效,相信我

整体测试:

class Program
{
    static void Main(string[] args)
    {
        var x = new XElement("root", new XElement("t", new XAttribute("xmlns", "")), new XAttribute("aaab", "bb"));
        Console.WriteLine(x);
        RemoveEmptyNamespace(x);
        Console.WriteLine(x);
    }

    private static void RemoveEmptyNamespace(XElement element)
    {
        XAttribute attr = element.Attribute("xmlns");
        if (attr != null && string.IsNullOrEmpty(attr.Value))
            attr.Remove();
        foreach (XElement el in element.Elements())
            RemoveEmptyNamespace(el);
    }
}
Run Code Online (Sandbox Code Playgroud)