我有一个具有以下结构的XMl文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FlashMemory>
<FlashItems>
<FlashItem>
<Keyword KID="1234">XY</Keyword>
<Header Version="1">XY</Header>
<Gap DivisibleBy="8">XY</Gap>
<Datatype DID="12345">XY</Datatype>
<Length>2</Length>
<ProductionSteps>
<ProductionStep>
<Step>XY</Step>
<Source>XY</Source>
<Value>XY/Value>
<DocTarget>
<Target>None</Target>
</DocTarget>
</ProductionStep>
</ProductionSteps>
</FlashItem>
<FlashItem>
.
.
.
</FlashItem>
</FlashItems>
</FlashMemory>我希望删除所有<FlashItem></FlashItem>节点,其中<Step>值与某些值相等。我尝试过LINQ,但是查询的结果总是null。
XDocument xmlDoc = XDocument.Load("test.xml");
xmlDoc.Descendants("FlashItems")
.Elements("FlashItem")
.Elements("ProductionSteps")
.Elements("ProductionStep")
.Elements("Step")
.Where(x => x.Value == "testvalue").Remove();在C#中有这样的建议吗?
更新:
var nodes = xmlDoc.Descendants("FlashItem");
var x = (from element in nodes
where element.Element("ProductionSteps")
.Element("ProductionStep")
.Element("Step").Value == "HecuProduction"
select element);
foreach (var query in x)
{
query.Element("Flashitem").Remove();
}在这种情况下,选择是有效的,我需要删除的所有节点都在x中,但是当我尝试删除时,我会得到一个空引用异常。
发布于 2022-11-16 10:45:47
你的代码确实有效..。但是,您没有删除要查找的父节点--您正在移除步骤节点本身。
试试看:
using System.Xml.Linq;
XDocument xmlDoc = XDocument.Load("./test.xml");
var nodesToRemove = xmlDoc.Descendants("FlashItems")
.Elements("FlashItem")
.Elements("ProductionSteps")
.Elements("ProductionStep")
.Elements("Step")
.Where(x => x.Value == "testvalue");
foreach (var node in nodesToRemove) {
node.Parent.Parent.Parent.Remove();
}https://stackoverflow.com/questions/74458371
复制相似问题