![](/img/trans.png)
[英]How to remove parent node in an XML if it has a child node with specific value in C#
[英]C# Delete a specific XML node by attribute value, (xyz.parent.child.remove(xyz) is not an option
<ul>
<li>1</li>
<li status="deleted">2</li>
<li>3</li>
<ul>
因此,我碰巧擁有那些漂亮的XML,並且我必須刪除所有狀態狀態為DELETED的節點。 問題是,有時我會遇到“ LI”,如果您使用xyz.parent.child.remove(xyz),我會碰到“ LI”,您會刪除父ul下的每個li,這確實很糟糕。 哦,我差點忘了那里有40種不同的標簽,它們可以具有這種強大的狀態屬性(即使用控制文件,在其中指定要清除的標簽)。
我試過的
foreach (var tag in controlTags)
{
try
{
if(doc.Descendants(tag).Where(p => p.Attribute("status").Value == "deleted").Any())
{
doc.Descendants(tag).Where(p => p.Attribute("status").Value == "deleted").Remove();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
(從控制文件中獲取可能的標簽名稱)
for (int i = 0; i < elemList.Count; i++)
{
if (elemList[i].OuterXml.Contains("deleted"))
{
elemList[i].ParentNode.RemoveChild(elemList[i]);
}
直到我碰到li標簽,這才是有前途的:(
有什么建議么? 謝謝!
您可以使用以下方式:
XDocument doc = XDocument.Parse("<ul><li>1</li><li status=\"deleted\">2</li></ul>");
var desc = doc.Descendants();
for(int i = desc.Count() - 1; i >= 0; i--)
{
XElement xe = doc.Descendants().ElementAt(i);
if (xe.HasAttributes)
foreach (XAttribute xa in xe.Attributes())
if (xa.Name == "status" && xa.Value == "deleted")
{
xe.Remove();
break;
}
}
這將導致XDocument文檔中沒有包含“ status = Deleted”的XElement。
that you cannot use foreach since we have to traverse the list in opposite direction because we are removing elements. 您不能使用foreach,因為因為我們要刪除元素,所以我們必須以相反的方向遍歷列表。 而且我們從原始來源請求元素,而不是克隆的元素。
xe.Remove()方法從其父級中刪除當前元素,因此我們不會自己調用父級,也不會與其他同名元素發生沖突
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.