I can remove an xml node using
XmlNode node = newsItem.SelectSingleNode("XYZ");
node.ParentNode.RemoveChild(node);
But what if I want to remove multiple nodes at once, for example XYZ,ABC,PQR
?
Is there any way to remove all of these nodes at once or do I have to remove them one by one?
NOTE: XYZ,ABC,PQR
being at the same level(ie they all have same parent)
Nothing is inbuilt when using the XmlDocument
API, but you could write a utility extension method, for example:
public static void Remove(this XmlNode node, string xpath)
{
var nodes = node.SelectNodes(xpath);
foreach (XmlNode match in nodes)
{
match.ParentNode.RemoveChild(match);
}
}
then call:
newsItem.Remove("XYZ|ABC|PQR");
If you can change to the XDocument
API, then things may be different.
think you could do something like that using linq to xml.
var listOfNodesToRemove = new[]{"XYZ", "ABC", "PQR"};
var document = XDocument.Load(<pathtoyourfile>);
document.Descendants
.Where(m => listOfNodesToRemove.Contains(m.Name.ToString())
.Nodes()
.Remove();
That would depend very much on the structure (nesting) etc.
But basically yes, for a handful of unrelated elements, select and remove them one at a time.
You could combine them to some extent:
List<string> RemoveNames = ...
var toBeRemoved = doc.Descendants().Where(d => RemoveNames.Contains(d.name));
foreach (var element in toBeRemoved.ToList()) ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.