如何使用c#基于xml的内容从xml中删除整个节点

时间:2012-10-19 05:15:34

标签: c# xml xml-parsing

我使用LoadXml加载下面的xml。我需要根据使用C#的条件删除整个<site> .... </site>节点。

如下:

  XmlDocument xdoc= new XmlDocument(); 
  xdoc.LoadXml(xmlpath); 
  string xml = xdoc.InnerXml.ToString();

  if(xml.Contains("href"+"\""+ "www.google.com" +"\"")
  {
  string removenode = "";  // If href=www.google.com is present in xml then remove the  entire node. Here providing the entire <site> .. </site>
  xml.Replace(removenode,"");
  }

它不是用null替换节点

XML是:

 <websites>
 <site>
 <a xmlns="http://www.w3.org/1999/xhtml" href="www.google.com"> Google </a>
 </site>
 <site>
 <a xmlns="http://www.w3.org/1999/xhtml" href="www.hotmail.com"> Hotmail </a>
 </site>
 </websites>

2 个答案:

答案 0 :(得分:1)

以下示例删除包含href属性包含www.google.com的任何元素的网站元素

using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            const string frag = @" <websites>
 <site>
 <a xmlns=""http://www.w3.org/1999/xhtml"" href=""www.google.com""> Google </a>
 </site>
 <site>
 <a xmlns=""http://www.w3.org/1999/xhtml"" href=""www.hotmail.com""> Hotmail </a>
 </site>
 </websites>";

            var doc = XDocument.Parse(frag);

            //Locate all the elements that contain the attribute you're looking for
            var invalidEntries = doc.Document.Descendants().Where(x =>
            {
                //Get the href attribute from the element
                var hrefAttribute = x.Attribute("href");
                //Check to see if the attribute existed, and, if it did, if it has the value you're looking for
                return hrefAttribute != null && hrefAttribute.Value.Contains("www.google.com");
            });

            //Find the site elements that are the parents of the elements that contain bad entries
            var toRemove = invalidEntries.Select(x => x.Ancestors("site").First()).ToList();

            //For each of the site elements that should be removed, remove them
            foreach(var entry in toRemove)
            {
                entry.Remove();
            }

            Debugger.Break();
        }
    }
}

答案 1 :(得分:0)

我认为您需要使用适当的XML和XPath。试试以下

XmlNodeList nl = xDoc.DocumentElement.SelectNodes("Site");

foreach(XmlNode n in nl)
{
    if(n.SelectSingleNode("a").Attributes("href").Value == "www.google.com")
    {
        n.ParentNode.RemoveChild(n);
    }

}

希望有所帮助。

Milind