Search code examples
xmlxsltxpathxpathnavigator

XPath - determine if a tree has only one type of a "leaf" node


I need an XPath expression that verifies that an XML list element has only a certain type of node. example:

I need to know if the list has only images.

<?xml version="1.0" encoding="UTF-8"?>

<mc type="group"> 
  <mc type="list"> 
    <mc type="group"> 
      <mc type="image"/> 
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
    </mc> 
  </mc> 
</mc>

the above XML is TRUE

<?xml version="1.0" encoding="UTF-8"?>

<mc type="group"> 
  <mc type="list"> 
    <mc type="group"> 
      <mc type="image"/> 
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
      <mc type="text"/>
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
    </mc>  
    <mc type="group"> 
      <mc type="image"/> 
    </mc> 
  </mc> 
</mc>

the above XML is FALSE


Solution

  • Use:

    not(//mc[not(mc) and @type[not(. = 'image')]])
    

    This evaluates to true() if and only if there isn't a "leaf" mc element the string-value of whose type attribute is different from the string "image".

    Explanation: Proper use of the "double-negation law".