XmlNodeList remove empty elements

I use this function to remove all empty elements in my xml file:
XmlNodeList emptyElements = doc.SelectNodes(@"//*[not(node())]");
for (int j = emptyElements.Count - 1; j >= 0; j--)
{
    emptyElements[j].ParentNode.RemoveChild(emptyElements[j]);
}

How can I change the script to only remove empty elements with the name category?
<category name="test" />
Jesper ChristensenProgrammerAsked:
Who is Participating?
 
käµfm³d 👽Connect With a Mentor Commented:
Try:

XmlNodeList emptyElements = doc.SelectNodes(@"//*[not(node()) and @name='test']");

Open in new window

0
 
Jesper ChristensenProgrammerAuthor Commented:
Hi.
Thank you for your reply.
But it´s <category i want to remove.
There is serveal different names:
<category name="test1" />
<category name="test2" />
<category name="test2" />

So something like
XmlNodeList emptyElements = doc.SelectNodes(@"//*[not(node()) and NODENAME='category']");
0
 
Jesper ChristensenProgrammerAuthor Commented:
I solved it by:
XmlNodeList emptyElements = doc.SelectNodes(@"//*[not(node()) and @name!='']");
0
 
käµfm³d 👽Commented:
But it´s <category i want to remove
Oh. Sorry, I misread this:

How can I change the script to only remove empty elements with the name category?

as "name attribute." My apologies. Instead of the *, why not use "category"?

e.g.

XmlNodeList emptyElements = doc.SelectNodes(@"//category[not(node())]");

Open in new window

0
 
Jesper ChristensenProgrammerAuthor Commented:
Thank you very much. It works even better
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.