【问题标题】:Flatten xml hierarchy using XSLT使用 XSLT 展平 xml 层次结构
【发布时间】:2018-08-25 08:09:51
【问题描述】:

我想使用 XSLT 将嵌套 xml 转换为扁平化 xml。

传入的xml结构类似,但传入的xml节点名称会改变,所以想动态处理

示例输入

<?xml version="1.0" encoding="UTF-8"?>
<queryResponse>
  <Account>
    <Id>0010</Id>
    <Name>AA</Name>
    <RecordTypeId>0122/RecordTypeId>
    <RecordType>
      <Id>012</Id>
      <DeveloperName>Legal_Associate</DeveloperName>
    </RecordType>
  </Account>
  <Account>
    <Id>0011</Id>
    <Name>BB</Name>
    <RecordTypeId>0123</RecordTypeId>
    <RecordType>
      <Id>013</Id>
      <DeveloperName>Legal_Associate</DeveloperName>
    </RecordType>
  </Account>
 </queryResponse>

预期输出

<?xml version="1.0" encoding="UTF-8"?>
<queryResponse>
  <Account>
    <Id>0010</Id>
    <Name>AA</Name>
    <RecordTypeId>0122</RecordTypeId>
    <RecordType.Id>012</RecordType.Id>
  <RecordType.DeveloperName>Legal_Associate</RecordType.DeveloperName>
  </Account>
  <Account>
    <Id>0011</Id>
    <Name>BB</Name>
    <RecordTypeId>0123<RecordTypeId>
    <RecordType.Id>013</RecordType.Id>    <RecordType.DeveloperName>Legal_Associate</RecordType.DeveloperName>
    </Account>
    </queryResponse>

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我可以为固定节点名实现它,但如何处理动态节点名

标签: xml xslt hierarchy flatten


【解决方案1】:

在发布问题时,您也应该发布尝试过的代码,然后我们可以告诉您更新情况。

这是您可以得到答案的代码:

<?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="2.0">

    <xsl:output method="xml" indent="yes"/>

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

    <xsl:template match="RecordType">
        <xsl:for-each select="*">
            <xsl:element name="{concat(name(..),'.',name())}">
                <xsl:apply-templates select="node()"/>
            </xsl:element>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>

【讨论】:

  • 你也可以在这里看到转换:xsltransform.net/jxN8NpY
  • 非常感谢 Amrendra,继续更新代码。我能够做到这一点,但是有没有办法为所有具有子节点的节点做到这一点。而是放置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多