xml - 如何使用 xsl 替换(动态)特定的 xml 元素
问题描述
输入 xml 这是输入 XML。
<?xml version="1.0" encoding="UTF-8"?>
<enc xmlns="v9">
<rnp xmsns="v2">
<ele1 line="1">
<ele2/>
</ele1>
</rnp>
<Request xmlns="v1">
<Request xmlns="v2">
<Info xmlns="v3">
<Country>US</Country>
<Part>A</Part>
</Info>
</Request>
</Request>
</enc>
我想用 v2 标签替换“Request with namespce v1”。
XSL:这是我用过的 xsl。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:variable name="var1">
<xsl:value-of select="local-name()"/>
</xsl:variable>
<xsl:copy>
<xsl:choose>
<xsl:when test="$var1='Request'">
<xsl:element name="{local-name()}" namespace="v2">
<xsl:apply-templates select="@* | node()"/>
</xsl:element>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="@*|node()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
在此先感谢。我是 xsl 的新手
解决方案
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:v1="v1"
exclude-result-prefixes="v1">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- You namespaces do not have a prefix, just the URL. So v1 would be considered
the URL (even though it doesn't look like one). So, you have to declare your
namespace like I have above. And, use the prefix in the template match.
Also, after transformation the child Request node will not have the v2
namespace shown because it inherits it from the parent Request node that was
just changed. But, it is in the namespace.
-->
<xsl:template match="v1:Request">
<xsl:element name="Request" namespace="v2">
<xsl:apply-templates select="node()|@*"/>
</xsl:element>
</xsl:template>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- android - 是否有在 android API 17+ 中定义目录选择器的本地方法?
- python - 为什么python抛出错误:AttributeError:'numpy.ndarray'对象没有属性'append'?
- javascript - 我能否确定浏览器中的可访问性功能是否处于活动状态?
- android - 如何在 Jetpack Compose 中制作手动可滚动选取框(通过触摸或鼠标/触摸板滚动)?
- aframe - 移动鼠标时桌面版本出错(cursor.js)
- angular - 将 aws-exports.js 移动到另一个 Angular 项目?
- modelica - 从 Dymola 导出具有大参数数组的 FMU
- c - 我无法弄清楚我是如何错误地创建了这个文件的
- python - python中的枕头矩形不让我有足够的论据
- php - 如何在 Drupal 8 的 hook_views_pre_execute 中将查询结果限制为 0?