Link to home
Start Free TrialLog in
Avatar of FrenchJericho
FrenchJericho

asked on

XPath to select nodes where child node is absent or empty?

In the following XML, I would like to select all employees without a middle name either because the node is empty or because the node is absent. In this example, the result would be Bill Gates and Larry Elison.

<Employees>
  <Employee>
    <FirstName>Bill</FirstName>
    <MiddleName></MiddleName>
    <LastName>Gates</LastName>
  </Employee>
  <Employee>
    <FirstName>George</FirstName>
    <MiddleName>W</MiddleName>
    <LastName>Bush</LastName>
  </Employee>
  <Employee>
    <FirstName>Larry</FirstName>
    <LastName>Elison</LastName>
  </Employee>
Avatar of b1xml2
b1xml2
Flag of Australia image

XPath statement
===============
//Employee[string-length(normalize-space(MiddleName)) != 0]
ASKER CERTIFIED SOLUTION
Avatar of b1xml2
b1xml2
Flag of Australia 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
in fact, the following would be sufficient
//Employee[string-length(normalize-space(MiddleName)) = 0]
XML Document
============
<?xml version="1.0" encoding="iso-8859-1"?>
<Employees>
 <Employee>
   <FirstName>Bill</FirstName>
   <MiddleName></MiddleName>
   <LastName>Gates</LastName>
 </Employee>
 <Employee>
   <FirstName>George</FirstName>
   <MiddleName>W</MiddleName>
   <LastName>Bush</LastName>
 </Employee>
 <Employee>
   <FirstName>Larry</FirstName>
   <LastName>Elison</LastName>
 </Employee>
</Employees>

XSLT Document
-------------
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt" version="1.0"
 exclude-result-prefixes="msxsl">
<xsl:output method="xml" encoding="iso-8859-1" indent="yes" />
<xsl:template match="/">
<Employees>
<xsl:copy-of select="//Employee[string-length(normalize-space(MiddleName)) = 0]" />
</Employees>
</xsl:template>
</xsl:stylesheet>

Output
========
<?xml version="1.0" encoding="iso-8859-1"?>
<Employees>
<Employee>
<FirstName>Bill</FirstName>
<MiddleName></MiddleName>
<LastName>Gates</LastName>
</Employee>
<Employee>
<FirstName>Larry</FirstName>
<LastName>Elison</LastName>
</Employee>
</Employees>