[英]How to remove a entire node from xml based on content of xml using c#
I am loading the below xml using LoadXml. 我正在使用LoadXml加载以下xml。 I need to remove the entire <site> .... </site>
node based on a condition using C#. 我需要根据条件使用C#删除整个<site> .... </site>
节点。
Followed: 追随者:
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,"");
}
It is not replacing the node with null 它没有用null替换节点
The XML is: 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>
Here's an example that removes the site element containing any element with an href
attribute containing www.google.com
这是一个示例,该示例删除包含任何元素的site元素,该元素的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();
}
}
}
I think you need to use proper XML and XPath for this. 我认为您需要为此使用适当的XML和XPath。 Try following 尝试跟随
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);
}
}
Hope that helps. 希望能有所帮助。
Milind 米林德
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.