XSLT:我可以使用 xslt 更新 xml 节点中的值吗? [英] XSLT:Can I update value in xml node using xslt?

查看:33
本文介绍了XSLT:我可以使用 xslt 更新 xml 节点中的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有一个像 xml

For example I have a xml like

 <books>
   <book id="1">
     <title id="11" name="Basic XML"/>
     <price id="12" amount="500"/>
     <quantity id="13" number="10"/>
   </book>
 </books>

是否可以将Basic XML"一书的名称更新为Basic XSLT"或使用 XSLT 更改任何节点的任何其他属性?如果是的话,谁能给我一些关于如何做的例子?

Can update the name of the book "Basic XML" to "Basic XSLT" or change any other attributes of any node using XSLT? If yes, can anyone give me some examples on how to do it?

提前致谢.

推荐答案

这种转变:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <my:reps>
  <repAttr name="name" value="Basic XSLT"/>
  <repAttr name="amount" value="300"/>
  <repAttr name="number" value="20"/>
 </my:reps>

 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match=
   "@*[name()=document('')/*/my:reps/*/@name]">

   <xsl:attribute name="{name()}">
    <xsl:value-of select=
    "document('')/*/my:reps/*[@name=name(current())]/@value"/>
   </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

应用于提供的 XML 文档时:

<books>
    <book id="1">
        <title id="11" name="Basic XML"/>
        <price id="12" amount="500"/>
        <quantity id="13" number="10"/>
    </book>
</books>

产生想要的、正确的结果:

<books>
   <book id="1">
      <title id="11" name="Basic XSLT"/>
      <price id="12" amount="300"/>
      <quantity id="13" number="20"/>
   </book>
</books>

说明:

  1. 身份规则/模板按原样"复制每个节点.

  1. The identity rule/template copies every node "as-is".

身份模板被匹配任何属性的单个模板覆盖,该属性的名称可以作为 repAttr 元素的 name 属性之一的值找到在 my:reps 元素(嵌入在 XSLT 样式表中的参数)中指定.

The identity template is overriden by a single template matching any attribute whose name can be found as value of one of the name attributes of a repAttr element that is specified in the my:reps element (parameters embeded in the XSLT stylesheet).

在这种情况下,属性将使用相同的名称和新值重新创建(不复制),在相应的 repAttr 元素(其 value代码>属性).

In this case the attribute is re-created (not copied) with the same name and with the new value, specified in the corresponding repAttr element (its value attribute).

这篇关于XSLT:我可以使用 xslt 更新 xml 节点中的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆