簡體   English   中英

從XDocument刪除節點

[英]Remove node from XDocument

我有一個xml配置文件,試圖從中刪除節點。 我的xml文檔如下

<appSettings>
  <add key="value1" value="27348614" />
  <add key="value2" value="123432" />
  <add key="removeMe" value="removeMeAsWell" />
</appSettings>

我嘗試了以下方法

public void removeNode(XDocument AppStoreXML, string FOPath)
{
    var newElement = new XElement("add",
             new XAttribute("key","removeMe" ),
            new XAttribute("value", "removeMeAsWell"));
    AppStoreXML.Root.Descendants("appSettings")
            .First(s => s.Attribute("key").Value == "removeMe")
            .Remove(); //this returns the error Sequence contains no matching element
    //newElement.Remove(); this try returns no matching parent

    AppStoreXML.Save(FOPath);
}

有人知道我在做什么錯嗎?

這就是問題:

AppStoreXML.Root.Descendants("appSettings")

您正在嘗試查找appSettings后代元素這些元素也稱為 appSettings並具有指定的屬性。 您需要add元素:

AppStoreXML.Root.Descendants("add")

另外,您可能希望將First()更改為Where這樣,您就可以找到多個要刪除的元素。

暫無
暫無

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

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