【问题标题】:XSLT to transform xml in specific formatXSLT 以特定格式转换 xml
【发布时间】:2021-03-20 11:23:11
【问题描述】:

当前 XML 的样子

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
    <attribute>
        <name>Attr1</name>
        <value>Attr1 Value 1</value>
    </attribute>
    <attribute>
        <name>Attr2</name>
        <value>Attr 2 Value 1</value>
        <value>Attr 2 Value 2</value>
    </attribute>
</document>

我希望新的 xml 看起来像以下 ....

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <document>
        <Attr1>           
            <value>Attr1 Value 1</value>
        </Attr1>
        <Attr2>
            <value>Attr 2 Value 1</value>
            <value>Attr 2 Value 2</value>
        </Attr2>
    </document>

我想使用 xslt 来实现这种转换……我的 xslt 不起作用

【问题讨论】:

  • 请就您在尝试完成此操作时遇到的困难提出一个具体问题。否则看起来你只是在找人为你做你的工作。

标签: xml xslt xpath xslt-1.0 xslt-2.0


【解决方案1】:

解决办法如下:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

  <xsl:template match="/document">
    <document>
      <xsl:apply-templates />
    </document>
  </xsl:template>

  <xsl:template match="/document/attribute">
    <xsl:element name="{name}">
      <xsl:copy-of select="value" />
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

这样做的主要困难是您需要创建一个具有动态名称的元素。这就是&lt;xsl:element name="{name}"&gt; 的用途。您可以在大括号之间放置任何 xpath 表达式。在这里,我们想要 /document/attribute 匹配的(希望是唯一的)名称节点。

【讨论】:

  • 我使用了一种稍微不同的方式来实现我的解决方案... w3.org/1999/XSL/Transform">
【解决方案2】:

我使用了不同的方式来处理上述问题...

    <?xml version="1.0" encoding="UTF-8"?>
<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="attribute">
        <xsl:element name="{name}">
            <xsl:apply-templates select="node()|@*"/>           
        </xsl:element>          
    </xsl:template>
    
    <xsl:template match="name"/>    
</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多