【问题标题】:Creating a list using xslt使用 xslt 创建列表
【发布时间】:2015-01-17 12:49:57
【问题描述】:

我有以下 XML

<?xml version="1.0" encoding="UTF-8"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <FirstName>John</FirstName>
  <LastName>Peter</LastName>
  <Initial>T</Initial>
</Employee>

在 XSLT 1.0 中,我想编写一个 XSLT 从上面的 xml 生成下面的 XML。谁能帮我写这个 xslt?

<?xml version="1.0" encoding="UTF-8"?>
<ArrayOfstringVariable xmlns="http://schemas.abc.org/2004/07/"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <stringVariable>
    <name>FirstName</name>
    <value>John</value>
  </stringVariable>
  <stringVariable>
    <name>LastName</name>
    <value>Peter</value>
  </stringVariable>
  <stringVariable>
    <name>Initial</name>
    <value>T</value>
  </stringVariable>
</ArrayOfstringVariable>

【问题讨论】:

    标签: xslt


    【解决方案1】:

    遵循 XSLT

    <?xml version="1.0" encoding="UTF-8" ?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:output method="xml" omit-xml-declaration="no"
           encoding="UTF-8" indent="yes" />
      <xsl:template match="Employee">
        <ArrayOfstringVariable>
          <xsl:apply-templates select="*"/>
        </ArrayOfstringVariable>
      </xsl:template>
      <xsl:template match="*">
        <stringVariable>
          <name>
            <xsl:value-of select="local-name()"/>
          </name>
          <value>
            <xsl:value-of select="."/>
          </value>
        </stringVariable>
      </xsl:template>
    </xsl:stylesheet>
    

    当应用于您问题的示例输入 XML 时,会产生以下输出:

    <?xml version="1.0" encoding="UTF-8"?>
    <ArrayOfstringVariable>
      <stringVariable>
        <name>FirstName</name>
        <value>John</value>
      </stringVariable>
      <stringVariable>
        <name>LastName</name>
        <value>Peter</value>
      </stringVariable>
      <stringVariable>
        <name>Initial</name>
        <value>T</value>
      </stringVariable>
    </ArrayOfstringVariable>
    

    如果您希望在输出 XML 中的 ArrayOfStringVariable 元素中包含命名空间,可以通过两个调整来完成:将 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 添加到 xsl:stylesheet 声明并将 &lt;ArrayOfstringVariable 调整为 &lt;ArrayOfstringVariable xmlns="http://schemas.abc.org/2004/07/" &gt; &lt;xsl:template match="Employee"&gt; 并在&lt;xsl:template match="*"&gt; 处将&lt;stringVariable&gt; 调整为&lt;stringVariable xmlns="http://schemas.abc.org/2004/07/"&gt;

    【讨论】:

    • 您的第一个模板和./* 中的./ 是多余的。
    • @JLRishe 感谢您提及,已经删除了第二个冗余并将有关第一个模板的信息添加到答案中,而不仅仅是删除它。用于从 root 开始,但此处不是必需的。
    • 为什么你匹配node()而不是*
    • @MathiasMüller 感谢您的提及。两者都适用于提供的示例,但* 可能更好。调整。如果有人注意到 cmets 想知道其中的区别,请参考 stackoverflow.com/questions/12071402/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多