0

临时数据.xml

<ArticleSet>
<Article>
    <LastName>Chang</LastName>
    <ForeName>K W</ForeName>
    <Affiliation>Department of Surgery, Army General Hospital, Taiwan, Republic of
    China.</Affiliation>
</Article>
<Article>       
    <LastName>Ferree</LastName>
    <ForeName>B A</ForeName>
    <Affiliation>Children's Hospital Medical Center, Cincinnati, Ohio.</Affiliation>        
</Article>
<Article>
    <LastName>Dyck</LastName>
    <ForeName>P</ForeName>
    <Affiliation>Department of Neurosurgery, University of Southern California, Los Angeles.</Affiliation>      
</Article>
<Article>
    <LastName>Lonstein</LastName>
    <ForeName>J E</ForeName>
    <Affiliation>Minnesota Spine Center, Minneapolis 55454-1419.</Affiliation>      
</Article>
</ArticleSet>

国家.xml

<Countries>
    <Country>
        <id>1</id>
        <name>Los Angeles</name>
        <code>ad</code>
    </Country>
    <Country>
        <id>2</id>
        <name>Republic of China</name>
        <code>ae</code>
    </Country>
    <Country>
        <id>3</id>
        <name>China</name>
        <code>af</code>
    </Country>
    <Country>
        <id>4</id>
        <name>Ohio</name>
        <code>ag</code>
    </Country>
</Countries>

XQuery 代码

declare variable $tokens:="";
declare variable $aff:="";
for $article in doc("tempdata.xml")/ArticleSet/Article
  let $aff:=data($article/Affiliation)
  let $aff:=replace($aff,'[;,.]',',')
  for $tokens in tokenize($aff,',')
    for $countries in doc("countries.xml")/Countries/Country
      return if($countries/name= normalize-space($tokens))
        then <Country>{data($countries/name)}</Country>

此 XQuery 代码将Affiliation标记中的字符串tempdata.xml与文件中的国家列表 相匹配,Countries.xml并打印国家名称。首先,从属关系字符串被标记化,每个标记都与可用国家列表匹配。

输出

<Country>Republic of China</Country>
<Country>Ohio</Country>
<Country>Los Angeles</Country>

我想<Country>-</Country>为没有找到国家的字符串打印一个标签。例如在 4th Affiliation 中,没有国家,所以在这种情况下,我想插入一个基于连字符的标签。所以我的问题是在哪里写 else 部分,以便我可以获得以下输出。

所需输出

<Country>Republic of China</Country>
<Country>Ohio</Country>
<Country>Los Angeles</Country>
<Country>-</Country>
4

1 回答 1

0

您当前的查询可能会<Country>为每篇文章返回多个元素,每个匹配的隶属关系一个。您最多依赖一个现有的匹配项。您可以收集所有匹配项,"-"作为后备添加,然后获取该序列的第一个候选者:

for $article in doc("tempdata.xml")/ArticleSet/Article
let $country :=
  for $aff in tokenize($article/Affiliation, '[;,\.]')
  where doc("countries.xml")/Countries/Country/name = normalize-space($aff)
  return normalize-space($aff)
return <Country>{($country, '-')[1]}</Country>
于 2019-01-21T09:29:58.393 回答