[英]Query to remove last result using LINQ to XML
I am having trouble parsing an xml file . 我在解析xml文件时遇到问题。 A sample is below.
下面是一个样本。
<G_LOG>
<LINE>9206</LINE>
<TEXT>Generating
</TEXT>
</G_LOG>
<G_LOG>
<LINE>9207</LINE>
<TEXT>Inserted Actual
</TEXT>
OK , so this is just a snapshot of thousands of nodes in the file. 好的,所以这只是文件中数千个节点的快照。 I need to search for the TEXT "Inserted Actual" and not only remove this node , but the previous node as well.
我需要搜索TEXT“Inserted Actual”,不仅要删除此节点,还要删除上一个节点。 So it would find the text on line 9207 and remove 9206 as well.
所以它会在第9207行找到文本并删除9206。 (removing everything in the above snippet)
(删除上面代码段中的所有内容)
I can search for the lines I want to remove . 我可以搜索我想删除的行。
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);
}
But I am unsure of how to obtain the previous node and remove it as well (without buckets of code)?. 但我不确定如何获取前一个节点并将其删除(没有代码桶)?
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();
}
A couple of things to note: 有几点需要注意:
from
flattens out each node and its previous node into one sequence from
变平的每个节点和其先前的节点为一个序列 .ToList()
eagerly evaluates the query, ensuring we don't remove a node while evaluating .ToList()
急切地评估查询,确保我们在评估时不删除节点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.