【发布时间】:2013-10-09 16:17:44
【问题描述】:
我想转换这个xml:
<Root>
<Result>
<Message>
<Header>
<!-- Hundreds of child nodes -->
</Header>
<Body>
<Node1>
<!-- Hundreds of child nodes -->
<Node2>
<!-- Hundreds of child nodes -->
<Node3>
<!-- Hundreds of child nodes -->
<NodeX>value 1 to be changed</NodeX>
<!-- Hundreds of child nodes -->
<Node4>
<!-- Hundreds of child nodes -->
<NodeY>value 2 to be changed</NodeY>
</Node4>
</Node3>
</Node2>
</Node1>
</Body>
<RealValuesRoot>
<!-- These two nodes -->
<Value ID="1">this value must replace the value of Node X</Value>
<Value ID="2">this value must replace the value of Node Y</Value>
</RealValuesRoot>
</Message>
</Result>
<!-- Hundreds to thousands of similar MessageRoot nodes -->
</Root>
进入这个xml:
<Root>
<Result>
<Message>
<Header>
<!-- Hundreds of child nodes -->
</Header>
<Body>
<Node1>
<!-- Hundreds of child nodes -->
<Node2>
<!-- Hundreds of child nodes -->
<Node3>
<!-- Hundreds of child nodes -->
<NodeX>this value must replace the value of Node X</NodeX>
<!-- Hundreds of child nodes -->
<Node4>
<!-- Hundreds of child nodes -->
<NodeY>this value must replace the value of Node Y</NodeY>
</Node4>
</Node3>
</Node2>
</Node1>
</Body>
</Message>
</Result>
<!-- Hundreds to thousands of similar MessageRoot nodes -->
</Root>
输出几乎与输入相同,除了以下更改:
- X 和 Y 节点值必须替换为 /RealValuesRoot/Value 节点的值。
- 必须从输出中删除 /RealValuesRoot 节点。
- xml 的其余部分在输出中必须保持不变。
“值”节点具有唯一 ID,表示消息正文中的唯一 xpath,例如ID 1 引用 xpath /Message/Body/Node1/Node2/Node3/NodeX。
我必须用微软的xslt 1.0版!!
我已经有了一个可以正常工作的 xslt,可以做任何我想做的事情,但我对性能并不满意!
我的 xslt 工作如下:
我创建了一个全局字符串变量,其作用类似于键值对,类似于:1:xpath1_2:xpath2_ … _N:xpathN。此变量将“Value”节点的 ID 与消息正文中需要替换的节点相关联。
xslt 从根节点开始递归迭代输入 xml。
-
我计算当前节点的 xpath,然后执行以下操作之一:
- 如果当前 xpath 与全局列表中的 xpath 之一完全匹配,则我将其值替换为相应“Value”节点的值并继续迭代。
- 如果当前 xpath 引用“RealValuesRoot”节点,那么我会忽略该节点(不要将其复制到输出中)并继续递归迭代。
- 如果当前 xpath 不存在于全局 ID-xpath 字符串中,则我将完整节点复制到输出并继续迭代。 (例如在 /Message/Header 节点中发生这种情况,该节点永远不会包含任何需要替换的节点)
- 如果当前 xpath 部分匹配全局列表中的 xpath 之一,那么我只需继续递归迭代,直到达到上述 3 种情况之一。
如前所述,我的 xslt 工作正常,但我想尽可能提高性能,请随时提出一个全新的 xslt 逻辑!欢迎您的意见和建议!
【问题讨论】:
-
他们真的叫
<Node1>、<Node2>等吗? -
当然不是 :-) 它们只是用来表达层次结构
-
嗯,这会影响解决方案。它们到底是怎么称呼的?
-
+1 用于发布完整且语法有效的输入和所需的输出,并准确描述您的问题,顺便说一句。大多数人都不做这两件事。
-
我的例子中的 X 和 Y 节点可以是 FirstName 和 LastName,其余节点可以是任何东西。