Flatten xml hierarchy using XSLT

喜你入骨 提交于 2019-12-25 18:44:17

问题


I would like to convert a nested xml to flatten xml using XSLT.

Incoming xml Structure would be similar but the node names would change for the incoming xmls, so would like to handle in dynamically

Sample input

<?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>

Expected Output

<?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>

回答1:


While posting the question you should post the tried code as well hense we can tell you the updation.

Here is the code which you can achive your answer:

<?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>


来源:https://stackoverflow.com/questions/49317683/flatten-xml-hierarchy-using-xslt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!