替换表达式
替换表达式会将现有节点替换为包含零个或零个以上节点的新序列,或在保留节点标识的同时替换节点值。
语法
- do replace
- 替换表达式的起始关键字。
- TargetExpression
- 并非更新表达式的 XQuery 表达式。 如果表达式包含顶级逗号运算符,那么该表达式必须括在圆括号中。 TargetExpression
的结果必须是并非文档节点的单个节点。 如果 TargetExpression
的结果为文档节点,那么 DB2 XQuery
会返回错误。
如果未指定 value of 关键字,那么 TargetExpression 的结果必须是其父属性不为空的单个节点。
- value of
- 用于指定在替换 TargetExpression 节点值的同时保留节点标识的关键字。
- with
- 源表达式的起始关键字。
- SourceExpression
- 并非更新表达式的 XQuery 表达式。 如果表达式包含顶级逗号运算符,那么该表达式必须括在圆括号中。
如果指定 value of 关键字,那么 SourceExpression 求值时会作为文本节点构造函数的内容表达式处理。 SourceExpression 的结果是单个文本节点或空序列。
如果未指定 value of 关键字,那么 SourceExpression 的结果必须是节点序列。 SourceExpression 在求值时会作为括在元素构造函数中的表达式处理。 如果 SourceExpression 序列包含文档节点,那么文档节点会替换为其子代。 SourceExpression 序列必须由下列节点类型组成:
- 如果 TargetExpression 节点是属性节点,那么替换序列必须由零个或零个以上属性节点组成。
- 如果 TargetExpression 节点是元素、文本、注释或处理指令节点,那么替换序列必须由零个或零个以上元素、文本、注释或处理指令节点的某些组合组成。
下列更新是在指定 value
of 关键字后生成的:
- 如果 TargetExpression 节点是元素节点,那么 TargetExpression 节点的现有子代将替换为 SourceExpression 返回的文本节点。 如果 SourceExpression 返回空序列,那么 TargetExpression 节点的子代属性将为空。 如果 TargetExpression 节点包含属性节点,那么它们不受影响。
- 如果 TargetExpression 节点并非元素节点,那么 TargetExpression 节点的字符串值将替换为 SourceExpression 返回的文本节点的字符串值。 如果 SourceExpression 未返回文本节点,那么 TargetExpression 节点的字符串值将替换为零长度字符串。
未指定 value
of 关键字时,将生成以下更新:
- SourceExpression 节点会替换 TargetExpression 节点。 TargetExpression 节点的父节点会成为每个 SourceExpression 节点的父代。 SourceExpression 节点占据了节点层次结构中原来由 TargetExpression 节点占据的位置。
- TargetExpression 节点及其所有属性和后代将与节点序列分离。
示例
以下示例使用 DB2 SAMPLE 数据库中的 CUSTOMER 表。 在 CUSTOMER 表中,XML 列 INFO 包含客户地址和电话信息。
在以下示例中,变换表达式的 copy
子句会根据列 INFO 创建 XML 文档的副本。 替换表达式将替换 addr
元素及其子代:
xquery
transform
copy $mycust := db2-fn:sqlquery('select info from customer where cid = 1000')
modify
do replace $mycust/customerinfo/addr
with
<addr country="Canada">
<street>1596 14th Avenue NW</street>
<city>Calgary</city>
<prov-state>Alberta</prov-state>
<pcode-zip>T2N 1M7</pcode-zip>
</addr>
return $mycust
对 SAMPLE 数据库运行时,该表达式将使用替换后的地址信息返回以下结果:
<customerinfo Cid="1000">
<name>Kathy Smith</name>
<addr country="Canada">
<street>1596 14th Avenue NW</street>
<city>Calgary</city>
<prov-state>Alberta</prov-state>
<pcode-zip>T2N 1M7</pcode-zip>
</addr>
<phone type="work">416-555-1358</phone>
</customerinfo>
以下表达式会将客户电话元素 type 属性的值
home 替换为 personal:
xquery
transform
copy $mycust := db2-fn:sqlquery('select info from customer where cid = 1004')
modify
do replace value of $mycust/customerinfo/phone[@type="home"]/@type with "personal"
return $mycust对 SAMPLE 数据库运行时,该表达式将使用替换后的属性值返回以下结果:
<customerinfo Cid="1004">
<name>Matt Foreman</name>
<addr country="Canada">
<street>1596 Baseline</street>
<city>Toronto</city>
<prov-state>Ontario</prov-state>
<pcode-zip>M3Z 5H9</pcode-zip>
</addr>
<phone type="work">905-555-4789</phone>
<phone type="personal">416-555-3376</phone>
<assistant>
<name>Gopher Runner</name>
<phone type="home">416-555-3426</phone>
</assistant>
</customerinfo>
助理的电话属性的值尚未更改。
