0

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.

MmM ...
  • 131
  • 1
  • 2
  • 14
  • Given this sample XML, what do you want the XPath to return? – har07 Nov 01 '14 at 21:58
  • @har07 - probably true/false ... every b is the same or not. I know, it doesnt make a lot of sence here, in practice i need it for atribute. – MmM ... Nov 01 '14 at 22:31
  • Only stating *"but it doesnt work"* without telling exactly why it does not work and not providing a code example is not good style to ask. Especially if you feel unsure with the correct technical wording, showing your code example can help a lot. – hakre Nov 02 '14 at 10:51

2 Answers2

2

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
hakre
  • 193,403
  • 52
  • 435
  • 836
1

If you mean by "control" that you actually want to have a Boolean return value telling you if all <b> elements have the same value you could use this expression:

count(/root/a/b[. != ../b]) = 0

It determines the <b>'s whose value is not like the values of other <b>'s. If the count is greater than 1 there is mismatch in at least one b so that the expression will be false. If the result set is empty the count will be 0 and the expression will be true.

This answer was inspired by How can I use XPath to find the minimum value of an attribute in a set of elements?.

Community
  • 1
  • 1
Marcus Rickert
  • 4,138
  • 3
  • 24
  • 29