c# - 如何避免在新创建的 XElement 中获取空命名空间?

标签 c# xml namespaces xelement

我试图从另一个文件中删除 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

有什么想法吗?谢谢!!

最佳答案

列出了您的第二项努力,您的方向是正确的。将 xmlns="" 移动到下一个后代意味着 pageFooter 具有正确的 xmlns,但其其余后代则没有。使用这个:

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

关于c# - 如何避免在新创建的 XElement 中获取空命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10452365/

相关文章:

c# - 相同 LineSeries 的多色标记 - OxyPlot

python - 使用 python 创建循环来查找 pom.xml 文件中的依赖项

WCF 契约(Contract)和命名空间?

matlab - 在 Matlab 中定义全局常量

c# - 遍历 XML 架构失败。 (使用 System.Xml.Schema 和 C#)

C# 为 `WhereWithIndex` 编写类型签名

c# - 如何向目标用户发送推文?

java - Woodstox StAX - 如何关闭文本内容验证?

javascript - 如何在同一行上对齐 div Qweb 报告。 Odoo 14

php - composer 中命名空间自动加载的问题