Home > Net >  PHP: DomDocument & XPath - how to select empty elements?
PHP: DomDocument & XPath - how to select empty elements?

Time:11-01

Assume the following tree:

<root>
 <a></a>
 <b>  </b>
 <c>
 </c>
 <d>Hello world</d>
 <e><f>!!!</f></e>
</root>

I need to be able to select all empty tags, so a, b, and c in the above example. In my scenario, I consider b and c as being empty, despite them having white spaces.

Further, I would not consider e as being empty as it has a child.

How do I select all elements that do no have a child, whose text node is completely empty or comprises only of white spaces?

The following XPath would select a, but miss b and c:

`.//*[not(text())`]

My feeling is that I need to use normalize-space() somehow, but I'm not sure how.

CodePudding user response:

Yes, with XPath1 you gonna need normalize-space. Try this:

.//*[not(*)][not(normalize-space(text()))]

  • Related