嗨!我有一個具有以下結構的 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 elemet in nodes where elemet.Element("ProductionSteps").Element("ProductionStep").Element("Step").Value == "HecuProduction" select elemet);
foreach (var query in x)
{
query.Element("Flashitem").Remove();
}
在這種情況下,選擇作業正常,我需要洗掉的所有節點都在 中x,但是當我嘗試洗掉時,我得到一個空參考例外。
uj5u.com熱心網友回復:
你的代碼確實有效......但是你沒有洗掉你想要的父節點 - 你正在洗掉步驟節點本身。
試試這個:
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://www.uj5u.com/net/535007.html
標籤:C#。网XML林克
下一篇:.NET替換鍵匹配的值
