使用 XSLT 将名称/值对 XML 转换为元素 [英] Convert Name/Value Pair XML to Elements using XSLT

查看:32
本文介绍了使用 XSLT 将名称/值对 XML 转换为元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由名称/值对组成的 XML 文件,我需要使用 xslt 1 的格式,其中每个名称"是一个元素名称,其中包含内容中的值.下面是一个例子:

I have an XML file consisting of Name/Value pairs that I need in a format using xslt 1 where each "Name" is an element name with the Value in the contents. Here is an example:

输入:

<Root>
  <Entities>
    <Entity EntityName="Client">
      <Data Name="ADDR_City">Anytown</Data>
      <Data Name="ADDR_State">SC</Data>
      <Data Name="ADDR_Zip">23904</Data>
    </Entity>
  </Entities>
</Root>

输出:

<Root>
  <Entities>
    <Client>
      <ADDR_City>Anytown</ADDR_City>
      <ADDR_State>SC</ADDR_State>
      <ADDR_Zip>23904</ADDR_Zip>
    </Client>
  </Entities>
</Root>

Client 的 EntityName 不一定是唯一可行的方法...我主要关心的是将 Data Name="... 字段转换为正确的格式.感谢您的帮助!

The EntityName of Client is not necessarily the only way this would work...I'm mainly concerned with getting the Data Name="... fields into the correct format. Thanks for any help!

推荐答案

抱歉 - 我错过了 Entity 名称.更新假设基数很多 每个<实体>.我想我还需要指出,如果属性 EntityName 或 Name 具有无效的元素字符(例如空格),或者属性完全丢失,这将失败.

Edit : Apologies - I missed the Entity name. Updated assuming the cardinality is many <Entity> per <Entities>. I guess I also need to point out that this will fail if the attributes EntityName or Name have invalid element characters (e.g. space), or if the attributes are missing entirely.

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

  <xsl:template match="/Root">
    <Root>
      <xsl:for-each select="Entities">
        <Entities>
          <xsl:for-each select="Entity">
            <xsl:element name="{@EntityName}">
              <xsl:for-each select="Data">
                <xsl:element name="{@Name}">
                  <xsl:value-of select="./text()"/>
                </xsl:element>
              </xsl:for-each>
            </xsl:element>
          </xsl:for-each>
        </Entities>
      </xsl:for-each>
    </Root>
  </xsl:template>
</xsl:stylesheet>

这篇关于使用 XSLT 将名称/值对 XML 转换为元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆