【问题标题】:Convert string value as XML tag name将字符串值转换为 XML 标记名称
【发布时间】:2023-03-23 20:19:01
【问题描述】:

以下是我的要求。我们可以使用 XSLT 做到这一点吗?我想将 AttributeName 的值转换为策略下的标记,并将相应的 AttributeValue 转换为值。

输入:

<Policy>
    <Attributes>
        <AttributeName>is_policy_loan</AttributeName>
        <AttributeValue>Yes</AttributeValue>
    </Attributes>
    <Attributes>
        <AttributeName>is_policy_owners</AttributeName>
        <AttributeValue>Yes</AttributeValue>
    </Attributes>       
    <Attributes>
        <AttributeName>is_policy_twoyears</AttributeName>
        <AttributeValue>Yes</AttributeValue>
    </Attributes>       
</Policy>

输出:

<Policy>
    <is_policy_loan>Yes</is_policy_loan>
    <is_policy_owners>Yes</is_policy_owners>
    <is_policy_twoyears>Yes</is_policy_twoyears>
</Policy>

【问题讨论】:

  • 别忘了接受答案。

标签: xslt


【解决方案1】:

以下xsl 文件将完成这项工作:

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

  <!-- create the <AttributeName>AttributeValue</..> nodes -->
  <xsl:template match="//Attributes">
    <xsl:variable name="name" select="AttributeName" />
    <xsl:element name="{$name}">
      <xsl:value-of select="AttributeValue" />
    </xsl:element>
  </xsl:template>

  <!-- wrap nodes in a `Policy` node -->
  <xsl:template match="/">
    <Policy>
      <xsl:apply-templates/>
    </Policy>
  </xsl:template>
</xsl:stylesheet>

【讨论】:

  • 感谢 hek2mgl !!我会试试这个,让你知道结果。
【解决方案2】:

我会做的,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output method="xml" indent="yes" encoding="UTF-8" omit-xml-declaration="yes" />
   <xsl:template match="Policy">
      <xsl:element name="Policy">
         <xsl:apply-templates />
      </xsl:element>
   </xsl:template>
   <xsl:template match="Attributes">
      <xsl:variable name="name" select="AttributeName" />
      <xsl:element name="{$name}">
         <xsl:value-of select="AttributeValue" />
      </xsl:element>
   </xsl:template>
</xsl:stylesheet>

输出将是,

<Policy>
    <is_policy_loan>Yes</is_policy_loan>
    <is_policy_owners>Yes</is_policy_owners>       
    <is_policy_twoyears>Yes</is_policy_twoyears>       
</Policy>

【讨论】:

    猜你喜欢
    • 2015-04-02
    • 2010-12-21
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2015-07-26
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多