删除xml节点-Xelement [英] Remove xml node -Xelement

查看:86
本文介绍了删除xml节点-Xelement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件,只需删除特定的节点即可.节点名称将作为用户输入给出.如何删除已向用户请求的特定节点?

I have a xml file from which only specific nodes have to be removed. The node name will be given as input from the user. How to remove the specific nodes which have requested from the user?

<Customers>    
  <Customer>    
    <id>michle</id>
    <address>newjersy</address>    
  </Customer>    
  <Customer>    
    <id>ann</id>
    <address>canada</address>    
  </Customer>
</Customers>

我尝试过

var customer = new XElement("customer",
      from o in customers
      select 
          new XElement("id", id),
          new XElement("address", address)
        );

客户将包含一个新节点

<Customer>    
  <id>ann</id>
  <address>canada</address>    
</Customer>

doc.Element("customers").Elements(customer).ToList().Remove();

但是这不起作用.如何从xml中删除元素?

but this is not working. How can I remove the element from the xml?

推荐答案

Tom,

尝试一下...

private static void RemoveNode(string sID)
    {
        XDocument doc = XDocument.Load(@"D:\\Projects\\RemoveNode.xml");

        var v = from n in doc.Descendants("Customer")
                     where n.Element("id").Value == sID
                     select n;
        v.Remove();
        doc.Save(@"D:\\Projects\\RemoveNode.xml");
    }

当我使用

RemoveNode("michle");

希望这会有所帮助.

这篇关于删除xml节点-Xelement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆