大家我有一個問題,關于如何從我的 xml 檔案中洗掉一個元素塊,同時只知道其中一個專案的文本值。有數百個相同的塊,唯一的區別是 ID 值和我知道洗掉塊的文本。
public static void deleteBlock() {
XElement xelement = XElement.Load(@"C:\Program Files (x86)\Tools\VisualStudioProjects\bausteine\modul.xml");
foreach (XElement xEle in xelement.Descendants("SW.Blocks.CompileUnit"))
{
var complete = xEle;
foreach(var item in xEle.Descendants("Text"))
{
if (item.Value=="The only thing i know to delete the Block")
{
complete.Remove();
break; // The Answer
}
}
xelement.Save(@"C:\Program Files(x86)\Tools\VisualStudioProjects\Baustein_1.xml");
}
我雖然可以先查找名稱為 SW.Blocks.CompileUnit 的元素,然后在其中查找 Text 值,如果它與我的匹配,則它應該洗掉該塊并且它應該遍歷所有塊。它會找到我想要的塊,但會洗掉其他所有內容并保存我想要洗掉的塊。然后它給了我空例外。
<SW.Blocks.CompileUnit ID="85" CompositionName="CompileUnits">
<AttributeList>
<ObjectList>
<MultilingualText ID="86" CompositionName="Comment">
<ObjectList>
<MultilingualTextItem ID="87" CompositionName="Items">
<AttributeList>
<Culture>de-DE</Culture>
<Text />
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
<MultilingualText ID="88" CompositionName="Title">
<ObjectList>
<MultilingualTextItem ID="89" CompositionName="Items">
<AttributeList>
<Culture>de-DE</Culture>
<Text>The Only thing i know to delete the Block</Text>
</AttributeList>
</MultilingualTextItem>
</ObjectList>
</MultilingualText>
</ObjectList>
</SW.Blocks.CompileUnit>
這是 xml 資料的塊之一。這也是我的代碼在洗掉其他所有內容時留下的那個。我希望我現在解釋得更好一點。我不知道為什么它會洗掉除塊之外的所有其他內容,以及為什么它給我一個空例外。提前致謝
uj5u.com熱心網友回復:
在這種情況下,我建議在確定需要洗掉哪些元素之后使用Remove擴展方法。這是一個完整的程式來演示這一點 - 它只需要一個合適的input.xml檔案。
using System.Linq;
using System.Xml.Linq;
var element = XElement.Load("input.xml");
element
.Descendants("SW.Blocks.CompileUnit")
.Where(x => x.Descendants("Text")
.Any(x => x.Value == "The only thing i know to delete the Block"))
.Remove();
element.Save("result.xml");
這不僅高效,而且比手動代碼一次通過后代更具自我描述性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431547.html
