xslt - XML 输出,元素值作为标签名称,下一个后续元素值作为创建标签的值
问题描述
我需要形成一个输出 xml,其中我需要将字段值作为标签,然后将后续的下一个字段值作为创建标签的值。
<PrimaryKey>
<PK1FeildName>CONNO</PK1FeildName>
<PK1Value>001</PK1Value>
<PK2FeildName>INNO</PK2FeildName>
<PK2Value>123</PK2Value>
<PK3FeildName>CONNO</PK3FeildName>
<PK3Value>011</PK3Value>
</PrimaryKey>
预期输出:
<PrimaryKey>
<CONNO>001</CONNO>
<INNO>123</INNO>
<CONNO>011</CONNO>
</PrimaryKey>
解决方案
如果我们认为元素总是成对出现,其中第一个元素的值是标签名称,第二个元素是值,那么这样可以:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="PrimaryKey">
<xsl:element name="PrimaryKey">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="*">
<xsl:if test="count(preceding-sibling::*) mod 2 = 0">
<xsl:element name="{.}">
<xsl:value-of select="following-sibling::*[1]"/>
</xsl:element>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
你可以在这里试试:https ://xsltfiddle.liberty-development.net/bwdws3
编辑以回答评论
示例 XML:
<Document>
<PrimaryKey>
<PK1FeildName>CONNO</PK1FeildName>
<PK1Value>001</PK1Value>
<PK2FeildName>INNO</PK2FeildName>
<PK2Value>123</PK2Value>
<PK3FeildName>CONNO</PK3FeildName>
<PK3Value>011</PK3Value>
</PrimaryKey>
<PrimaryKey>
<PK1FeildName>CONNO2</PK1FeildName>
<PK1Value>0012</PK1Value>
<PK2FeildName>INNO2</PK2FeildName>
<PK2Value>1232</PK2Value>
<PK3FeildName>CONNO2</PK3FeildName>
<PK3Value>0112</PK3Value>
</PrimaryKey>
</Document>
修改后的 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<xsl:element name="PrimaryKey">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
<xsl:template match="PrimaryKey/*">
<xsl:if test="count(preceding-sibling::*) mod 2 = 0">
<xsl:element name="{.}">
<xsl:value-of select="following-sibling::*[1]"/>
</xsl:element>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- python - Python Dask 在组合请求时导致错误
- google-apps-script - 将一行的内容复制到最后一行
- node.js - 如何防止用户在 Node.js / Express 中按下提交按钮
- matlab - 在不同的位置复制多个文件 Matlab
- python-3.x - 使用 selenium 的 Python 网络爬虫
- python - 如何在元组列表中查找部分字符串匹配
- javascript - 如何在 JS 中正确创建动态表?
- google-sheets - 无法计算 X 和 Y 为真的出现次数
- big-o - 关于算法复杂度的表达式
- javascript - 按名称从数组中删除项目