0

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

跟随:

  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>
4

2 回答 2

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();
        }
    }
}
于 2012-10-19T05:30:38.680 回答
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);
    }

}

希望有帮助。

米林德

于 2012-10-19T05:26:16.590 回答