【问题标题】:XSLT convert child node text to the parent's attributeXSLT 将子节点文本转换为父节点的属性
【发布时间】:2015-11-14 23:16:03
【问题描述】:

我正在尝试使用 XSL 来转换我的 XML 文档,以便某些子节点的文本值成为其父节点的属性。

这是我所拥有的:

<?xml version="1.0" encoding="UTF-8"?>
<property_data>
  <property>
    <property_descriptions>
      <property_description>
        <type>property</type>
        <description>property 1000 description</description>
      </property_description>
      <property_description>
        <type>rate</type>
        <description>text rate description</description>
      </property_description>
    </property_descriptions>
    <property_attributes>
      <property_id>1000</property_id>
    </property_attributes>
  </property>
    <property>
...
  </property>
</property_data>

这就是我想要实现的目标:

 <?xml version="1.0" encoding="UTF-8"?>
 <property_data>
  <property>
    <property_descriptions>
      <property_description type="property">property 1000 description</property_description>
      <property_description type="rate">text rate description</property_descriptions>
    <property_attributes>
      <property_id>1000</property_id>
    </property_attributes>
  </property>
    <property>
...
  </property>
</property_data>

我被困在需要选择孩子价值的部分。

编辑: 按照 michael.hor257k 的建议,我能够获得以下 .xsl 来完成这项工作:

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

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

    <xsl:template match="property_description">
        <property_description type="{type}">
            <xsl:value-of select="description"/>
        </property_description>
    </xsl:template>

</xsl:stylesheet>

【问题讨论】:

  • 请发布您当前的 XSLT,以便我们修复它,而不是从头开始。

标签: xml xslt


【解决方案1】:

这与 identity transform 模板一起应该提供预期的结果:

<xsl:template match="property_description">
    <property_description type="{type}">
        <xsl:value-of select="description"/>
    </property_description>
</xsl:template>

【讨论】:

最近更新 更多