midfde
asked on
How to delete a few of ML elements?
What is the best way of deleting unknown number of XML elements with the same tag, please.
Please see the code and its result for the context of the question:
Source code:
Please see the code and its result for the context of the question:
Source code:
class Program {
static void Main(string[] args) {
XmlDocument dom = new XmlDocument();
dom.LoadXml(@"<A><a /><a /><a /><a /></A>");
foreach (XmlElement x in dom.GetElementsByTagName("a")){
Console.WriteLine(x.Name);
}
try{
foreach (XmlElement x in dom.GetElementsByTagName("a")){
Console.WriteLine("--" + x.Name);
x.ParentNode.RemoveChild(x);
}
} catch (Exception e) { Console.WriteLine("Error::" + e.Message); }
Console.Read();
}
}
Output on the console is as follows:a
a
a
a
--a
Error::The element list has changed. The enumeration operation failed to continue.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
See my previous note.
ASKER
Sorry about my typo: xc2 --> zc2
I (as mostly C++ programmer) don't see any much difference between for() and foreach() and why for() could be less desired. But your solution is really working. That's weird, but those two lists created different ways behave different.
There's, AFAIK, no way to delete a node except ask the parent to do that.
There's, AFAIK, no way to delete a node except ask the parent to do that.
ASKER
>>...as mostly C++ programmer...
"C" - thinking remnant? What if XmlNodeList did not have its indexer?
"C" - thinking remnant? What if XmlNodeList did not have its indexer?
Yeah, kind of that. I've never heard a collection item can not be accessed by its index.
ASKER
I am not sure indexers and their counterpart for(i=0;...) are applicable for some widely used collections. See e.g., LINQ here.:
Thanks
ASKER
Your code does what I want, but...
For me it is not the best becuse I dislike two of its fetures:
1) It introduces unnecessary enumeration (I want to say: "delete all that..." rather than delete all with numbers ..." (met in my solution)
2) I'd like to somehow avoid using of the parent; I'd like to say "Delete this", rather than "Delete the child of the parent of this" (still to be met).
Anyway, your solution in a row with mine are illustrated in the attached iamge.