C# 从XML中删除指定命名空间中的所有节点

C# 从XML中删除指定命名空间中的所有节点,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我有一个XML文档,它在名称空间中包含一些内容。以下是一个例子: <?xml version="1.0" encoding="UTF-8"?> <root xmlns:test="urn:my-test-urn"> <Item name="Item one"> <test:AlternativeName>Another name</test:AlternativeName> <Price t

我有一个XML文档,它在名称空间中包含一些内容。以下是一个例子:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:test="urn:my-test-urn">
    <Item name="Item one">
        <test:AlternativeName>Another name</test:AlternativeName>
        <Price test:Currency="GBP">124.00</Price>
    </Item>
</root>
我目前并不过分担心名称空间声明是否仍然存在,因为现在我很乐意只删除指定名称空间中的内容。请注意,文档中可能有多个名称空间需要修改,因此我希望能够指定要删除内容的名称空间

我曾尝试使用
.subjects().Where(e=>e.Name.Namespace==“test”)
执行此操作,但这仅用于返回
IEnumerable
,因此它无法帮助我查找属性,如果我使用
.degenantNodes()
我看不到查询名称空间前缀的方法,因为它似乎不是XNode上的属性

我可以遍历每个元素,然后遍历元素上的每个属性,检查每个元素的
Name.Namespace
,但这似乎不雅观,也很难理解


有没有一种方法可以使用LINQ to Xml实现这一点?

遍历元素,然后遍历属性似乎不太难读懂:

var xml = @"<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:test='urn:my-test-urn'>
    <Item name='Item one'>
        <test:AlternativeName>Another name</test:AlternativeName>
        <Price test:Currency='GBP'>124.00</Price>
    </Item>
</root>";
var doc = XDocument.Parse(xml);
XNamespace test = "urn:my-test-urn";

//get all elements in specific namespace and remove
doc.Descendants()
   .Where(o => o.Name.Namespace == test)
   .Remove();
//get all attributes in specific namespace and remove
doc.Descendants()
   .Attributes()
   .Where(o => o.Name.Namespace == test)
   .Remove();

//print result
Console.WriteLine(doc.ToString());
var xml=@”
另一个名字
124
";
var doc=XDocument.Parse(xml);
XNamespace test=“urn:我的测试urn”;
//获取特定命名空间中的所有元素并删除
文件编号()
.Where(o=>o.Name.Namespace==test)
.Remove();
//获取特定命名空间中的所有属性并删除
文件编号()
.Attributes()
.Where(o=>o.Name.Namespace==test)
.Remove();
//打印结果
Console.WriteLine(doc.ToString());
输出:

<root xmlns:test="urn:my-test-urn">
  <Item name="Item one">
    <Price>124.00</Price>
  </Item>
</root>

124

试试看。我必须从根元素中提取名称空间,然后运行两个单独的LINQ:

  • 删除具有名称空间的元素
  • 删除命名空间中的属性
  • 代码:

    结果:

    <root xmlns:test="urn:my-test-urn">
      <Item name="Item one">
        <Price>124.00</Price>
      </Item>
    </root>
    
    <root>
      <Item name="Item one">
        <Price>124.00</Price>
      </Item>
    </root>
    
    
    124
    
    这并没有回答问题-属性
    test:Currency
    仍然存在
    .Descents
    返回可枚举的XElement。@MattJones抱歉,我确实漏掉了问题的这一部分,已修复。迭代元素,然后遍历属性看起来不太难读,IMHO。您认为呢?当然,您在
    .subjects()
    的返回值上使用了
    .Attributes()
    !这很好用,我喜欢它的可读性,而且当我看到你写的东西时,我真的拍了拍我的额头。看到这样的情景,我现在简直不敢相信我没有意识到我自己也能做到!非常感谢。它确实有效,但我有点喜欢@har07问题中的LINQ,但是有一个+1的变量。非常感谢。
    <root xmlns:test="urn:my-test-urn">
      <Item name="Item one">
        <Price>124.00</Price>
      </Item>
    </root>
    
    xDocument.Root.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
    
    <root>
      <Item name="Item one">
        <Price>124.00</Price>
      </Item>
    </root>