簡體   English   中英

查詢使用LINQ to XML刪除最后的結果

[英]Query to remove last result using LINQ to XML

我在解析xml文件時遇到問題。 下面是一個樣本。

<G_LOG>
  <LINE>9206</LINE>
  <TEXT>Generating 
</TEXT>
</G_LOG>
<G_LOG>
  <LINE>9207</LINE>
  <TEXT>Inserted Actual
</TEXT>

好的,所以這只是文件中數千個節點的快照。 我需要搜索TEXT“Inserted Actual”,不僅要刪除此節點,還要刪除上一個節點。 所以它會在第9207行找到文本並刪除9206。 (刪除上面代碼段中的所有內容)

我可以搜索我想刪除的行。

 XDocument xmlDoc = XDocument.Load(filename);
 var q = from c in xmlDoc.Descendants("G_LOG")
         where c.Element("TEXT").Value.Contains("Inserted Actual")
         select (string)c.Element("LINE");
 foreach (string name in q)
 {
     Console.WriteLine("Actuals Success on ID : " + name);           
 }

但我不確定如何獲取前一個節點並將其刪除(沒有代碼桶)?

XElement xmlDoc = XElement.Load("c:\\temp.xml");
 var q = xmlDoc.Descendants("G_LOG").Where(c=>c.Element("TEXT").Value.Contains("Inserted Actual")).Select(d=>d.Element("LINE"));
foreach(XElement elm in q)
{
if(elm.Parent.ElementsBeforeSelf().Count()!=0)
elm.Parent.PreviousNode.Remove();
elm.Parent.RemoveNodes();
}
var elementsToRemove =
    from logElement in xml.Descendants("G_LOG")
    where logElement.Element("TEXT").Value.Contains("Inserted Actual")
    from element in new[] { logElement, logElement.PreviousNode }
    select element;

foreach(var element in elementsToRemove.ToList())
{
    element.Remove();
}

有幾點需要注意:

  1. 第二from變平的每個節點和其先前的節點為一個序列
  2. .ToList()急切地評估查詢,確保我們在評估時不刪除節點

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM