Search code examples
xmlxqueryexist-db

Error logic at reading xml document with xquery?


I have a lot XML documents that contain <h1>text</h1> . for example :

<p>
 <h1>
   text-1
 </h1>
 a lot text
 <h1>
   text-2
 </h1>
</p>

I insert this code :

for $p in (1 to 351)
return <a href="{$p}">{data(doc(concat("/db/INDEX/",$p,".html"))//h1)}</a>

The result is This :

<a href="2"<----this is page number >
 text-1
 text-2
</a>
<a href="3"<----this is page number />

Notice: when in one page are two tag or more <h1> the texts show in one tag <a>

but i need this :

<a href="2">
 text-1
</a>
<a href="2">
 text-2
</a>

And when in a page are not <h1> tag , show empty <a>.


Solution

  • How about:

    for $h in collection("/db/INDEX")//h1
    let $i := replace(document-uri(root($h)), ".*/(.*)\.html", "$1")
    return
        <a href="{$i}">{string($h)}</a>