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 に答える