将 xml 属性和文本展平为同级元素

flatten xml attribute and text into sibling elements

我正在尝试转换一个 xml 文件,看起来像这样

<?xml version="1.0" encoding="UTF-8"?>
<Records xmlns="http://some.place.net">
    <Record>
         <length unit="in">96</length>
         <width unit="in">3.75</width>
         <height unit="in">1.75</height>
         <weight unit="lbs">8</weight>
    </Record>
</Records>

进入看起来像这样的东西

<?xml version="1.0" encoding="UTF-8"?>
<Records xmlns="http://some.place.net">
    <Record>
        <length>96</length>
        <lengthunit>in</lengthunit>
        <width>3.75</width>
        <widthunit>in</widthunit>
        <height>1.75</height>
        <heightunit>in</heightunit>
        <weight>8</weight>
        <weightunit>lbs</weightunit>
    </Record>
</Records>

我的 xlst 风格 sheet 是这样的。我不知道如何让新元素显示为前一个元素的同级元素

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

    <xsl:variable name="vNamespace" select="namespace-uri(/*)"/>

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

    <xsl:template match="@unit">
        <xsl:element name="{name(..)}{name()}" namespace="{$vNamespace}">
            <xsl:value-of select="."/>
        </xsl:element>
    </xsl:template>


</xsl:stylesheet>

这就是我最终得到的结果。

<Records xmlns="http://some.place.net">
  <Record>
    <length>
      <lengthunit>in</lengthunit>96</length>
    <width>
      <widthunit>in</widthunit>3.75</width>
    <height>
      <heightunit>in</heightunit>1.75</height>
    <weight>
      <weightunit>lbs</weightunit>8</weight>
  </Record>
</Records>

如果 select 元素而不是属性会更简单:

<xsl:template match="*[@unit]">
    <xsl:element name="{name()}" namespace="{$vNamespace}">
        <xsl:value-of select="."/>
    </xsl:element>
    <xsl:element name="{name()}unit" namespace="{$vNamespace}">
        <xsl:value-of select="@unit"/>
    </xsl:element>
</xsl:template>