如何使用XDocument删除数据?

时间:2013-06-26 11:29:30

标签: c# linq-to-xml

假设我有一个

下的xml文件
<DataBaseServers>
  <DataBaseServer id="1" title="IISDevdb1" address="Address1">
    <DataBases>      
      <database id="1" name="db1" userID="u1" password="p1" />
      <database id="3" name="db3" userID="u3" password="p3" />
    </DataBases>
  </DataBaseServer>
  <DataBaseServer id="2" title="iis2" address="Address2">
  <DataBases>      
      <database id="2" name="db2" userID="u2" password="p2" />    
    </DataBases>
  </DataBaseServer>
</DataBaseServers>

我想删除数据库id =“3”。

生成的xml将是

<DataBaseServers>
  <DataBaseServer id="1" title="IISDevdb1" address="Address1">
    <DataBases>      
      <database id="1" name="db1" userID="u1" password="p1" />     
    </DataBases>
  </DataBaseServer>
  <DataBaseServer id="2" title="iis2" address="Address2">
  <DataBases>      
      <database id="2" name="db2" userID="u2" password="p2" />    
    </DataBases>
 </DataBaseServer>
</DataBaseServers>

如果我删除数据库id =“2”,则xml将显示为

<DataBaseServers>
  <DataBaseServer id="1" title="IISDevdb1" address="Address1">
    <DataBases>      
      <database id="1" name="db1" userID="u1" password="p1" />
      <database id="3" name="db3" userID="u3" password="p3" />
    </DataBases>
  </DataBaseServer>
  <DataBaseServer id="2" title="iis2" address="Address2"/>
 </DataBaseServers>

如何使用XDocument进行操作?

2 个答案:

答案 0 :(得分:0)

您需要遍历XDocument的元素列表并使用element.Remove(); method.as:

XDocument document = XDocument.Load(Server.MapPath(@"Doc\abc.xml")); ;
        foreach (XElement element in document.Document.Descendants("database").ToList())
        {
            if(element.Attribute("id").Value == Convert.ToString(3))
            element.Remove();
        }
        document.Save(Server.MapPath(@"Doc\abc1.xml"));

请参阅Removing nodes from XDocument

答案 1 :(得分:0)

好的,我明白了

xdoc.Descendants("database")
.Where(xa => xa.Attribute("id").Value == Convert.ToString(3))
.Remove();