Search code examples
xmlloopsxpathxsdschematron

Xpath - how control every element value with others?


EXAMPLE:
My XML:

<root>
    <a>
        <b>1</b>
        <b>1</b>
        <b>2</b>
    </a>
    <a>
        <b>1</b>
        <b>2</b>
    </a>
    <a>
        <b>1</b>
    </a>
</root>
  • A now, how to control that every "b" element has got only the same one value(not only "1")?
  • Is it possible? I found only, but it doesnt work: //a/b != ./b
  • I have no idea except some loop or count by value in element ... but it cant in xpath, or not?

Thanks for replies.


Solution

  • To get the number of different values for all /*/a/b element nodes, you can count the distinct values of those elements:

    count(/*/a/b[not(. = preceding::b)])
    

    This expression will return 1 if there is one distinct value, 2 if two (as in your case) or 0 if there are no /*/a/b elements in the document.

    PHP Example:

    <?php
    
    $buffer = <<<XML
    <root>
        <a>
            <b>1</b>
            <b>1</b>
            <b>2</b>
        </a>
        <a>
            <b>1</b>
            <b>2</b>
        </a>
        <a>
            <b>1</b>
        </a>
    </root>
    XML;
    
    $doc = new DOMDocument();
    $doc->loadXML($buffer);
    $xpath = new DOMXPath($doc);
    
    echo $xpath->evaluate('count(/*/a/b[not(. = preceding::b)])');  # echoes 2