【问题标题】:how do I avoid getting the empty namespace in newly created XElement?如何避免在新创建的 XElement 中获取空命名空间?
【发布时间】:2012-05-04 16:06:22
【问题描述】:

我正在尝试从另一个文件中删除然后将 pageFooter 添加到 xml 文档:

XNamespace rep = "http://developer.cognos.com/schemas/report/8.0/";

//remove pageFooter
doc.Root.Descendants().Where(e=>e.Name == rep + "pageFooter").Remove();

//create and load pagefooter from file
XElement pageFooter = XElement.Load(@"C:\pageFooter.xml");

我得到的是空的命名空间:

<pageFooter xmlns="">
    <contents>
         ..............

我尝试了以下所有方法来将命名空间添加到新元素,但没有任何效果:

XElement pagefooter = new XElement(rep+"pageFooter"); 
pageFooter = XElement.Load(@"C:\pageFooter.xml");        
//this has no effect

pageFooter.Name = rep.GetName(pageFooter.Name.LocalName);
//this moves the xmlns="" to the next descendant, <contents>

pageFooter.Add(rep);   
//this has no effect

pageFooter.SetAttributeValue("xmlns", rep);
//this results an empty pageFooter

有什么想法吗?谢谢!!

【问题讨论】:

    标签: c# xml namespaces xelement


    【解决方案1】:

    列出了您的第二次努力,您走在了正确的轨道上。将xmlns="" 移动到下一个后代意味着pageFooter 有正确的xmlns,但它的其余后代没有。使用这个:

    foreach (var d in pagefooter.DescendantsAndSelf())
        d.Name = rep + d.Name.LocalName;
    

    【讨论】:

    • 谢谢,这行得通!让我感到困惑的是,为什么只有下一个后代获得了空的命名空间,而不是全部?我仍然没有得到那部分。你可以解释吗?再次感谢!!
    • 如果命名空间没有明确定义,它会继承其父命名空间。所以之前,pageFooter 及其所有后代的 xmlns 都是“”。然后你进行了更改,pageFooter 的 xmlns 发生了更改,但它的所有后代仍然是“”,这通过将 xmlns="" 添加到 contents 元素来表示。
    【解决方案2】:

    无论何时您执行pageFooter = XElement.Load(file),您都会将 pageFooter 中的任何内容替换为文件的内容。预先设置rep 命名空间不会影响XElement.Load()

    您确定 XML 文件有 pageFooter 的命名空间吗?

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2011-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多