从现有 xml 生成 xml,没有一个节点

Generate xml from existing xml without one node

我想从现有节点生成一个 xml 但按 ID 删除一个节点: 我的 xml 是:

<PartyList>
  <Party Id="1" In="true" Out="true"/>
  <Party Id="2" In="true" Out="false"/>
  <Party Id="3" In="true" Out="true"/>
</PartyList>

并尝试使用以下方法 select 节点,但无法删除它:

xmlNode = xmlDoc.SelectSingleNode("/PartyList/Party[@Id='3']"));

如何删除它?有没有更好的方法使用 linq to xml?

XmlDocument 中删除选定的元素可以按如下方式完成:

xmlNode = xmlDoc.SelectSingleNode("/PartyList/Partyx[@Id='3']");
xmlNode.ParentNode.RemoveChild(xmlNode);
xmlDoc.Save("path_for_the_updated_file.xml");

或使用 LINQ-to-XML 的 XDocument :

var doc = XDocument.Load("path_to_your_xml_file.xml");
doc.Root
   .Elements("Partyx")
   .First(o => (int)o.Attribute("Id") == 3)
   .Remove();
doc.Save("path_for_the_updated_file.xml");