.net - 使用 LINQ to XML 删除节点,排除具有特定属性的节点

标签 .net vb.net linq-to-xml

我有这样的 xml 文件:

<group>
  <First_group>
  </First_group>
  <Second_group>
    <Name number="1">
    </Name>
    <Name number="2">
    </Name>
    <Name number="3">
    </Name>
  </Second_group>
  <Third_group>
  </Third_group>
</group>

我想删除节点名称,不包括属性 = 1 的节点

这是代码:

Dim doc As XDocument = XDocument.Load("c:\temp\node.xml")
doc.Root.Element("Second_group").Elements("Name").Attributes("number").Value > 1.Remove()

但是这不起作用。

最佳答案

它甚至无法编译(根据您发布的代码)。您的方向是正确的,但您的查询有点偏离。

Attributes("number").Value

无法编译,因为 Value 不是 Attributes 的成员 - Attributes 返回属性的集合与名称匹配,并且您无法将集合与单个值进行比较(至少不是很容易)。

您真正需要的是一个 Where 子句,传入 Where 子句的表达式以作为谓词求值。像这样:

Doc.Root.Element("Second_group").
Elements("Name").
Where(Function(x) CInt(x.Attribute("number").
Value) > 1).
Remove()

注意上面的代码分为几行,这样人们就可以看到整个查询,而无需水平滚动。对于 VB.Net,它应该在一行上,如下所示:

Doc.Root.Element("Second_group").Elements("Name").Where(Function(x) CInt(x.Attribute("number").Value) > 1).Remove()

在上面的示例中,Where 子句采用一个谓词来检查所有选定名称元素的数字属性。 Value 返回一个字符串,因此我使用 CInt 将其转换为数字。然后,删除“Second_group”中属性“number”大于 1 的所有“Name”元素。

因此,在上述语句之后,您的 XML 将如下所示:

<group>
  <First_group>
  </First_group>
  <Second_group>
    <Name number="1">
    </Name>
  </Second_group>
  <Third_group>
  </Third_group>
</group>

以上代码在 VS 2012 的控制台应用程序中进行了测试。

关于.net - 使用 LINQ to XML 删除节点,排除具有特定属性的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16867912/

相关文章:

.net - 在运行时获取 OutofMemoryException 消息 "Insufficient memory to continue the execution of the program"

c# - 如何防止代码契约自动创建前提条件检查?

.net - 使用 .Net 进行文本挖掘、事实提取、语义分析

c# - 如何使用 Linq To XML 获取元素值

c# - 将 XElement 添加到特定位置的另一个 XElement

c# - 使用 LINQ to XML,如何根据序号位置连接两组数据?

c# - 在程序集中创建一个 Hello World 库函数并从 C# 中调用它

.net - 是否可以拥有共享/静态依赖属性?

vb.net - OLEDB 将 CSV 导入 VB.NET 数据表,将 '-' 读取为 0

vb.net - 使用 VB.net 以编程方式更改 Windows 窗体上控件的位置?