Link to home
Start Free TrialLog in
Avatar of midfde
midfdeFlag for United States of America

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:
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();
        }
    }

Open in new window

Output on the console is as follows:
a
a
a
a
--a
Error::The element list has changed. The enumeration operation failed to continue.

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of zc2
zc2
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of midfde

ASKER

Thank you, xc2.
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.User generated image
Avatar of midfde

ASKER

See my previous note.
Avatar of midfde

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.
Avatar of midfde

ASKER

>>...as mostly C++ programmer...
"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.
Avatar of midfde

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