Skip to content
Advertisement

How to find Self-Closing Tags with org.w3c.dom

Does anybody know, how to find self closing tags of the XML document?
I am able to get all the elements of specific type, but I am unable to find elements, that are self closing and also, I need to find elements, with no attributes.

JavaScript

My XML file has two types of myTag tags:

  1. Pair tags, that contains another nested child elements <myTag><someElementHere /></myTag>
  2. Self-closing tags, that are specifying some other behaviour <myTag/>

Is there a mechanism, to find this kind elements? The one possible thing would be, to match the regex of self closing tags, but I was thinking of some other solution possible.

Advertisement

Answer

Self closing tags have no children but so do empty tags. That said, XPath could be used to find elements with no children or with attributes

Given

JavaScript

Find elements with no children with //*[count(./descendant::*) = 0 and count(./text()) = 0]

JavaScript

Find elements with attributes with xpath //*[count(./@*)> 0]

JavaScript

Note: XPath is language agnostic so it should work in java.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement