【问题标题】:XSLT transformation to eliminate nestingsXSLT 转换以消除嵌套
【发布时间】:2021-07-31 18:50:40
【问题描述】:

我正在尝试使用 XSLT 删除输入 XML 中不必要的嵌套。以下是我的输入大纲:

<?xml version="1.0" encoding="UTF-8"?>
<Application>
  <Applicants>
     <Applicant>
       <Id> 1 </Id>
     </Applicant>
     <Applicant>
       <Id> 2 </Id>
     </Applicant>
  </Applicants>
</Application>

现在,转换后这是我想要的输出:

<Application>
  <Applicants>
     <Id> 1 </Id>
  </Applicants>
  <Applicants>
     <Id> 2 </Id>
  </Applicants>
</Application>

有人可以帮我解决这个问题吗?我是 XSLT 转换的新手

【问题讨论】:

  • 你试过什么?为什么它不起作用?
  • 我尝试使用 来匹配 并删除 标记。正如我所说,我是新手,任何建议都表示赞赏。
  • 不要将其视为“删除”某些东西。把它想象成“不复制”的东西。所以,基本上你想将“申请人/申请人”的所有匹配转换为“申请人”。
  • 是的,正确,对于每个 ,输出应该有一个 。输出不应有 本身。
  • 它可以写成 3 个简单的模板: 1. Applicants:删除节点并将模板应用到子节点。 2.Applicant:重命名为Applicants 并将模板应用到子级 3. 其他所有内容:按原样复制(身份模板)

标签: c# xml xslt


【解决方案1】:

正如评论中提到的,手头的任务可以在 3 个模板中执行:

  • Applicants:删除节点并将模板应用到子节点。
  • Applicant:重命名为申请人并将模板应用到孩子
  • 其他所有内容:按原样复制(身份模板)
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:strip-space elements="*"/>
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="Applicants">
  <xsl:apply-templates select="node()"/>
</xsl:template>

<xsl:template match="Applicant">
  <xsl:element name="Applicants">
    <xsl:apply-templates select="@*|node()"/>
  </xsl:element>
</xsl:template>

<!--Identity template, provides default behavior that copies all content into the output -->
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 好的!我正在尝试这个:
【解决方案2】:

或者简单地说:

XSLT 1.0

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

<xsl:template match="/Application">
    <xsl:copy>
        <xsl:for-each select="Applicants/Applicant">
            <Applicants>
                <xsl:copy-of select="Id"/>
            </Applicants>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2014-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多