简体   繁体   中英

XQuery fn:deep-equal - comparing text from XPath with string literal

I'm trying to use XQuery function fn:deep-equal to compare sections of XML documents and I'm getting unexpected behaviour. When comparing XPath value with string literal, function returns false.

For example following code

let $doc :=
  <root>
    <child><message>Hello</message></child>
  </root>

let $message := <message>Hello</message>

let $value := $doc/child/message/text()
let $compareDirectly := fn:deep-equal($value, "Hello") (: -> false :)
let $compareAsString := fn:deep-equal(fn:concat($value, ""), "Hello") (: -> true :)
let $comparePath := fn:deep-equal($value, $message/text()) (: -> true :)

return
  <results>
    <value>{$value}</value>
    <directly>{$compareDirectly}</directly>
    <asString>{$compareAsString}</asString>
    <path>{$comparePath}</path>
  </results>

Executed using Saxon, XQuery program generates following XML

<?xml version="1.0" encoding="UTF-8"?>
<results>
    <value>Hello</value>
    <directly>false</directly>
    <asString>true</asString>
    <path>true</path>
</results>

I'd expect $compareDirectly to be true (same as two other examples), but fn:deep-equal does not seem to work as I would intuitively expect. I'm wondering whether this is correct behaviour.

Is there any better wah how to compare two XML nodes?

I'm lookig for some generic solution which could be used for both XML snippets (like values of $doc or $message in example) and also for this special case with string literal.

From the spec :

To be deep-equal, they must contain items that are pairwise deep-equal; and for two items to be deep-equal, they must either be atomic values that compare equal, or nodes of the same kind, with the same name, whose children are deep-equal.

So this is why it doesn't return true when comparing a text node to an atomic type. In your other two examples you are comparing 2 string atomic types. It looks as if you don't need deep-equal, which compares nodes recursively. If that's the case, then you can just compare the strings:

$doc/child/message/string() eq $message/string()
=> true()

If there are other requirements, then you may need to update your example to demonstrate those more clearly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM