我有带有多个工作块的 xml。 仅当原始值不等于 null 时,我才想更改日期字段格式(从字符串到日期)。 另外,维护文件的结构和值也很重要
我有这样的xml文件
<header>
<serianl_num>123</serianl_num>
<type>11</type>
<body>
<direction>in</direction>
<worker>
<salary>1234</salary>
<name>aaa</name>
<gender>male</gender>
<date>20140101</date>
</worker>
<worker>
<salary>1234</salary>
<name>bbb</name>
<gender>feamle</gender>
<date>nil:true</date>
</worker>
</body>
</header>
这是我想要得到的预期输出结果
<header>
<serianl_num>123</serianl_num>
<type>11</type>
<body>
<direction>in</direction>
<worker>
<salary>1234</salary>
<name>aaa</name>
<gender>male</gender>
<date>2014-01-01</date>
</worker>
<worker>
<salary>1234</salary>
<name>bbb</name>
<gender>feamle</gender>
<date>nil:true</date>
</worker>
</body>
</header>
这是我尝试编写的xsl:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl=http://www.w3.org/1999/XSL/Transform xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance>
<xsl:output method="xml" indent="yes" xalan:indent-amount="2"
xmlns:xalan=http://xml.apache.org/xalan/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match = "header/body">
<xsl:for-each select = "worker">
<xsl:choose>
<xsl:param name="myDate" select ="string-length(date)"/>
<xsl:when test = "string-length($myDate)=8">
<xsl:copy>
<xsl:value-of select="concat(substring($myDate,1,4),'-',substring($myDate,5,2),'-',substring($myDate,7,2))"/>
</xsl:copy>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:attribute name="xsi:nil">true</xsl:attribute>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
但这没有用。 我将不胜感激任何帮助
我尝试在互联网上查找信息,我尝试了多次尝试以达到预期的结果,但没有成功。我将非常感谢任何解决问题的帮助或建议。
如果您想更改
date
element(不是 attribute)的值,则仅匹配 date
元素(甚至仅匹配 date
元素内的文本节点)并按原样复制其他所有内容.
另一个问题是您对
string-length(date)=8
的测试也适用于 <date>nil:true</date>
。所以你需要寻找另一个测试或者让测试更有选择性。尝试例如:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="date[string-length() = 8 and . != 'nil:true']/text()">
<xsl:value-of select="concat(substring(., 1, 4), '-', substring(., 5, 2), '-',substring(., 7, 2))"/>
</xsl:template>
</xsl:stylesheet>