【问题标题】:XML Transformation - Include element from "subnode" in parent as attributeXML 转换 - 将父级中“子节点”中的元素包含为属性
【发布时间】:2016-12-19 08:27:24
【问题描述】:

我正在尝试通过 XSLT 转换 XML 文件。 输出 XML 需要包含元素作为属性。

我的输入文件如下所示:

<queryResponse>
 <entity>
  <DevicesDTO>
    <name>value</name>
    <type>value</type>
    <manufacturersNrs>
     <manufacturersNr>value</manufacturersNr>
    </manufacturersNrs>
  </DevicesDTO>
 </entity>
</queryResponse>

我的输出应该是这样的:

<Data>
 <Device name=xxx type=xxxx manufacturersNr=xxx />
</Data>

到目前为止,我已经成功地转换了我的 xml 并将名称和类型作为属性。 但是,manufacturersNrs 中包含了manufacturersNr,我不知道如何将其包含在它上面的节点中。

我的 xslt 文件现在看起来像这样:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

  <xsl:template match="devicesDTO">
    <Device>
      <xsl:for-each select="*">
        <xsl:attribute name="{name()}">
          <xsl:value-of select="text()"/>
        </xsl:attribute>

      </xsl:for-each>
    </Device>
  </xsl:template>
</xsl:stylesheet>

对于一个完整的 xslt 新手有什么提示吗? 我现在拥有的东西是我从各种来源拼凑而成的,所以如果我需要完全重写......就这样吧。

【问题讨论】:

    标签: xml xslt transformation


    【解决方案1】:

    如果您将 &lt;xsl:for-each select="*"&gt; 更改为 &lt;xsl:for-each select="descendant::*[not(*)]"&gt;,我认为您可以轻松解决问题。

    【讨论】:

    • 似乎成功了!你有机会解释这背后的逻辑吗?我还有一些其他文件有类似的问题,如果我能正确理解的话,我可能会解决它们:)
    • 您对select="*" 的原始尝试处理了一个子元素,我的建议是处理所有没有自己的子元素(表示为descendant::*[not(*)])的后代元素(descendant::*),所以在你的情况下它处理nametypemanufacturersNr,但不处理manufacturersNrs,因为该元素有一个子元素。
    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多