微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在XSLT中添加缺少的XML元素需要什么?

我正在尝试将 XML文件转换为更新版本.

我有以下源XML

<?xml version="1.0" encoding="utf-8" ?>
<config>
  <section name="abc">
    <key name="key1">My Key One</key>
  </section>
  <section name="def">
    <key name="key2">My Key Two</key>
  </section>
</config>

转换看起来像这样……但是,目标实际上可能看起来像这样,所以我不希望添加部分xyz如果已经存在:

<?xml version="1.0" encoding="utf-8" ?>
<config>
  <section name="abc">
    <key name="key1">My Key One</key>
  </section>
  <section name="def">
    <key name="key2">My Key Two</key>
  </section>
  <section name="xyz">
    <key name="key3">My Key Three</key>
  </section>
</config>

XSLT目前看起来像这样:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="config">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="@*|text()|comment()|processing-instruction()">
<xsl:copy-of select="."/>
</xsl:template>

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

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

</xsl:stylesheet>

这似乎复制了存在的东西.如果它实际上丢失了,如何添加我缺少的元素呢?

解决方法

尝试这样的事情:

<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:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="config">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
      <xsl:if test="not(section/@name='xyz')">
        <section name="xyz">
          <key name="key3">My Key Three</key>
        </section>
      </xsl:if>
    </xsl:copy>    
  </xsl:template>

</xsl:stylesheet>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。