0

我是 C# 的新手我有问题...我想selected node从我的XMl文件中删除我刚刚尝试使用此代码但我没有得到任何人的帮助

private void btnDelete_Click(object sender, EventArgs e)
{
    xdoc.Load(strFilename);
    string Xpath = string.Format("root/{0}/{1}",_strProCat,_strProdType);
    xdoc.SelectSingleNode(Xpath).RemoveAll();

    xdoc.Save(strFilename);
    MessageBox.Show("Deleted Successfully");
}

这是我的 Xml 文件

<root>
  <product category="Soaps">
   <product type="Washing">
     <product name="Rin">
      <Id>100</Id>
      <AvailProducts>30</AvailProducts>
      <Cost>20.00</Cost>
   </product>
  <product name="Tide">
    <Id>101</Id>
    <AvailProducts>30</AvailProducts>
    <Cost>15.00</Cost>
  </product>
 </product>
</product>
</root>

只是我想删除节点哪个产品name="Tide"

4

3 回答 3

1

您可以简单地使用以下代码:

private void btnDelete_Click(object sender, EventArgs e)
{
    var xDoc = XDocument.Load(strFilename);

    foreach (var elem in xDoc.Document.Descendants("product"))
    {
        foreach (var attr in elem.Attributes("name"))
        {
            if (attr.Value.Equals("Tide"))
                elem.RemoveAll();
        }
    }

    xDoc.Save(destinationFilename);
    MessageBox.Show("Deleted Successfully");
}

快乐的编码...

于 2012-10-08T12:46:54.843 回答
1

这样的事情应该这样做:

xdoc.Elements("product").Where(x=> x.Element("name").Value == "Tide").FirstOrDefault().Remove();
于 2012-10-08T12:47:08.307 回答
1

如果你想要XPathXmlDocument那么下面就是这样做的方法..

XmlDocument xdoc = new XmlDocument();
xdoc.Load(strFilename);
string Xpath = string.Format("root/product[@category='{0}']/product[@type='{1}']/product[@name='{2}']", "Soaps", "Washing", "Tide");
xdoc.SelectSingleNode(Xpath).RemoveAll();
xdoc.Save(strFilename);

更新

根据您的要求To Remove the empty node,尝试以下代码将空节点删除为

XmlNodeList emptyElements = xdoc.SelectNodes(@"//*[not(node())]");
for (int i = emptyElements.Count - 1; i > -1; i--)
{
     XmlNode nodeToBeRemoved = emptyElements[i];
     nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}

现在你最终的完整肉体代码看起来像

string Xpath = string.Format("root/product[@category='{0}']/product[@type='{1}']/product[@name='{2}']", "Soaps", "Washing", "Tide");                      
xdoc.SelectSingleNode(Xpath).RemoveAll();
XmlNodeList emptyElements = xdoc.SelectNodes(@"//*[not(node())]");

for (int i = emptyElements.Count - 1; i > -1; i--)
{
      XmlNode nodeToBeRemoved = emptyElements[i];
      nodeToBeRemoved.ParentNode.RemoveChild(nodeToBeRemoved);
}
xdoc.Save(strFilename);
于 2012-10-08T12:52:56.833 回答