我有以下XML文件:
<layout>
<layout-structure>
<layout-root id="layout-root">
<layout-chunk id="header-text">
<layout-leaf xref="lay-1.01"/>
<layout-leaf xref="lay-1.02"/>
</layout-chunk>
<layout-leaf xref="lay-1.03"/>
</layout-root>
<layout-root id="layout-root-two">
<layout-chunk id="header-text-two">
<layout-leaf xref="lay-1.04"/>
<layout-leaf xref="lay-1.05"/>
<layout-leaf xref="lay-1.06"/>
</layout-chunk>
<layout-leaf xref="lay-1.07"/>
</layout-root>
</layout-structure>
<realization>
<text xref="lay-1.01 lay-1.04"/>
<text xref="lay-1.02 lay-1.05"/>
<graphics xref="lay-1.03 lay-1.06" type="1"/>
<graphics xref="lay-1.07" type="2"/>
</realization>
</layout>
我想提取 graphics 元素的 xref 属性的值,以限制 for 子句中的输出功能如下所示。
declare function local:gfx($root, $graphics) {
let $graphic-xrefs := tokenize($graphics/@xref, " ")
for $layout-leafs in $root//layout-leaf[@xref = $graphic-xrefs]
return concat('"', $layout-leafs/@xref, '" ', $dotgraphics, ';', $newline)
};
然而,这会导致错误,因为 graphics 元素下的某些 xref 属性包含单个值,如<graphics xref="lay-1.07"/>
的情况。
是否可以使用tokenize来获取图形 / xref 值,还是应该使用其他方法?
答案 0 :(得分:1)
您可以尝试更改创建$graphic-xrefs
...
declare function local:gfx($root, $graphics) {
let $graphic-xrefs :=
for $xref in $graphics/@xref
return
tokenize($xref,' ')
for $layout-leafs in $root//layout-leaf[@xref = $graphic-xrefs]
return concat('"', $layout-leafs/@xref, '" ', $dotgraphics, ';', $newline)
};
答案 1 :(得分:0)
这不应该导致问题,因为如果分割字符串不在搜索字符串中,tokenize
将只返回整个字符串。
为了处理这种情况,普通的if (...) then ... else ...
语句可能很有用。此外,您可能希望使用try { ... } catch {...}
构造来处理意外情况。
当我运行此代码时,您的代码实际上按预期工作:
declare variable $t :=
<layout>
<layout-structure>
<layout-root id="layout-root">
<layout-chunk id="header-text">
<layout-leaf xref="lay-1.01"/>
<layout-leaf xref="lay-1.02"/>
</layout-chunk>
<layout-leaf xref="lay-1.03"/>
</layout-root>
<layout-root id="layout-root-two">
<layout-chunk id="header-text-two">
<layout-leaf xref="lay-1.04"/>
<layout-leaf xref="lay-1.05"/>
<layout-leaf xref="lay-1.06"/>
</layout-chunk>
<layout-leaf xref="lay-1.07"/>
</layout-root>
</layout-structure>
<realization>
<text xref="lay-1.01 lay-1.04"/>
<text xref="lay-1.02 lay-1.05"/>
<graphics xref="lay-1.03 lay-1.06" type="1"/>
<graphics xref="lay-1.07" type="2"/>
</realization>
</layout>;
declare function local:gfx($root, $graphics) {
let $graphic-xrefs := tokenize($graphics/@xref, " ")
for $layout-leafs in $root//layout-leaf[@xref = $graphic-xrefs]
return $layout-leafs/@xref
};
local:gfx($t, $t/realization/graphics[2])
请注意,代码段中的最后一个<layout>
实际上应该是一个结束语句。