使用XSLT修改xml文档

前端之家收集整理的这篇文章主要介绍了使用XSLT修改xml文档前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图了解是否有办法使用XSLT修改xml文档,还是有比XSLT更好的方法

说,我有一个像这样的xml:

<Feed xmlns="http://www.w3.org/2005/Atom">
<id>http://libx.org/libx2/libapps</id>
<entry>
<id>http://libx.org/libx2/libapps/2</id>
</entry>
<entry>
<id>http://libx.org/libx2/libapps/3</id>
</entry>
</Feed>

我想做以下的行动:

>修改Feed:id to(删除Feed文本:id)
>修改条目:id值,使“/”之后的最后一个数字值保留.

结果xml看起来应该是这样的:

<Feed xmlns="http://www.w3.org/2005/Atom">
<id></id>
<entry>
<id>2</id>
</entry>
<entry>
<id>3</id>
</entry>
</Feed>

谢谢,
索尼

解决方法

I. XSLT 1.0解决方案:

此XSLT 1.0转换适用于任何URL,而不对所有具有共同起始子字符串的URL进行任何假设:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="http://www.w3.org/2005/Atom">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="x:Feed/x:id/node()"/>

 <xsl:template match="x:entry/x:id/text()" name="eatSlashes">
  <xsl:param name="pText" select="."/>

  <xsl:choose>
   <xsl:when test="not(contains($pText,'/'))">
    <xsl:value-of select="$pText"/>
   </xsl:when>
   <xsl:otherwise>
    <xsl:call-template name="eatSlashes">
     <xsl:with-param name="pText" select=
                   "substring-after($pText,'/')"/>
    </xsl:call-template>
   </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

当应用于提供的XML文档时:

<Feed xmlns="http://www.w3.org/2005/Atom">
    <id>http://libx.org/libx2/libapps</id>
    <entry>
        <id>http://libx.org/libx2/libapps/2</id>
    </entry>
    <entry>
        <id>http://libx.org/libx2/libapps/3</id>
    </entry>
</Feed>

产生了想要的正确结果:

<Feed xmlns="http://www.w3.org/2005/Atom">
   <id/>
   <entry>
      <id>2</id>
   </entry>
   <entry>
      <id>3</id>
   </entry>
</Feed>

II. XSLT 2.0解决方案:

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:x="http://www.w3.org/2005/Atom">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="x:Feed/x:id/node()"/>

 <xsl:template match="x:entry/x:id/text()">
  <xsl:sequence select="tokenize(.,'/')[last()]"/>
 </xsl:template>
</xsl:stylesheet>

当应用于同一XML文档(上面)时,会产生相同的正确结果:

<Feed xmlns="http://www.w3.org/2005/Atom">
   <id/>
   <entry>
      <id>2</id>
   </entry>
   <entry>
      <id>3</id>
   </entry>
</Feed>

猜你在找的XML相关文章