如何从文件中删除XML元素?

9
在像这样的XML文件中:

<Snippets>
 <Snippet name="abc">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name="def">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>

当只给出属性名称(例如abcdef)时,如何删除元素?

你不需要WinForms标签。可能是重复的问题https://dev59.com/C1TTa4cB1Zd3GeqPrVjW - Renatas M.
4个回答

22

你可以尝试这样做:

string xmlInput = @"<Snippets>
 <Snippet name=""abc"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>

 <Snippet name=""def"">
   <SnippetCode>
   code goes here
   </SnippetCode>
 </Snippet>
</Snippets>";

// create the XML, load the contents
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlInput);

// find a node - here the one with name='abc'
XmlNode node = doc.SelectSingleNode("/Snippets/Snippet[@name='abc']");

// if found....
if (node != null)
{
   // get its parent node
   XmlNode parent = node.ParentNode;

   // remove the child node
   parent.RemoveChild(node);

   // verify the new XML structure
   string newXML = doc.OuterXml;

   // save to file or whatever....
   doc.Save(@"C:\temp\new.xml");
}

这太完美了。我的代码实际上大部分都一样,但是我在获取名称属性时遇到了困难。谢谢。 - dnclem
3
我讨厌别人抢在我前面完成某件事 :) 就是我写的代码。 - Leslie Hanks
@LeslieHanks:我也经常遇到这种情况 :-) - marc_s
1
@franz1:不,这是 XPath 标准的一部分:https://www.w3schools.com/xml/xpath_syntax.asp - XmlDocument 使用 XPath 表达式从 XML 文档中选择特定节点(或属性)。 - marc_s
@marc_s 您认为我可以在单个语句中将 @ 与析取符号结合起来吗?我想要查找一个节点,其中 x 属性或 y 属性或两者都等于指定的值。到目前为止,我声明了两个变量来存储每个属性的两个不同节点,并在 if 语句中的条件表达式中使用了析取。我想知道是否有更好的方法来使用所提到的 XPath,以便我可以最小化代码... - franz1
显示剩余3条评论

1

如果您能够使用LINQ to XML,那么这将变得非常容易:

var doc = XDocument.Load("input.xml");
var query = doc.Descendants("Snippet")
               .Where(x => (string) x.Attribute("name") == "def");

//  Using extension method
query.Remove();

(该问题被标记为.NET 2.0,但在2022年,可以合理地假设大多数用户可以使用LINQ to XML...)

0
  XElement xEmp = XElement.Load(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");
            //
            xEmp.Add(
                     new XElement("ToDo",
                      new XElement("Item", item),
                       new XElement("date", date),
                        new XElement("time", time),
                        new XElement("due", due),
                        new XElement("description", description))
            );
            xEmp.Save(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");`  XElement xEmp = XElement.Load(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");
            //
            xEmp.Add(
                     new XElement("ToDo",
                      new XElement("Item", item),
                       new XElement("date", date),
                        new XElement("time", time),
                        new XElement("due", due),
                        new XElement("description", description))
            );
            xEmp.Save(@"C://Users//Khulu//Documents//Visual Studio 2012//Projects//AMD//Schedule//ToDo.xml");`

0
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Snippet")
    let attr = node.Attribute("name")
    where attr != null && attr.Value == "abc"
    select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");

.Net 2.0

XmlDocument doc = new XmlDocument();
doc.Load("input.xml");
XmlNodeList nodes = doc.SelectNodes("//Snippet[@name='abc']");

现在你已经有了属性名为'abc'的节点,你可以循环遍历并删除它们。

你应该为 .net 2.0 添加标签。 - FosterZ
我最初编写了这段代码,但现在我正在使用NET 2,并且存在退级会导致问题的情况。 - dnclem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接