2012-10-19 16 views

回答

1

下面是一個例子,去除含有任何元素包含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(); 
     } 
    } 
} 
+0

大,它的工作。但我的XML也產生'<網站的xmlns =「ID的href屬性的網站元素:4457-211445-15151-151" > Google Hotmail'那麼它失敗說 「序列不包含任何元素」 – user1658567

+0

更換'變種的文檔,刪除...'無線第一個(y => y.Name.LocalName ==「site」))。ToList();'這是導致問題的命名空間 – mlorbetske

+0

@ user1658567是否解決了這個問題? – mlorbetske

0

我認爲你需要使用正確的XML和XPath本:

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,""); 
    } 

它沒有與空

的XML是替換節點。嘗試以下內容

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

相關問題