简体   繁体   中英

Multiple child nodes of the same name in xml to convert to xsl

Input XML

<Address country="USA" countryISO2Code="US">
    <Street addr="GH Nagar"/>
    <Street addr="Naboor"/>
    <Street addr="Besides Al Drive Inn"/>
</Address>

Expected Output response

"address": {
    "country": "USA",
    "countryISO2Code": "US",
    "Street1": "GH Nagar" ,
    "Street2": "Naboor" ,
    "Street3": "Besides Al Drive Inn" 
}       

can anyone suggest to write the xsl for the above please.

You can use this:

<xsl:output indent="yes" method="text"></xsl:output>
<xsl:template match="Address">
    <xsl:text>"address":{</xsl:text>
    <xsl:for-each select="@*">
        <xsl:value-of select="concat('&#xa;&quot;', local-name(.), '&quot;: &quot;', ., '&quot;,')"/>
    </xsl:for-each>
        <xsl:for-each select="Street">
            <xsl:text>&#xa;</xsl:text>
            <xsl:value-of select="concat('&quot;',local-name(.), position(), '&quot;: &quot;',@addr,'&quot;,')"/>
        </xsl:for-each>
    <xsl:text>&#xa;}</xsl:text>
</xsl:template>

Output

"address":{
"country": "USA",
"countryISO2Code": "US",
"Street1": "GH Nagar",
"Street2": "Naboor",
"Street3": "Besides Al Drive Inn",
}

It is not working as you suggested. can you please check the below. I am able to get the other values except the "Street" one's.

Request you to suggest the changes only for Street sections only.

my xsl is

<xsl:for-each select="./Address/Street">
    <xsl:text></xsl:text>
    <xsl:value-of select="concat('&quot;',local-name(.), position(), '&quot;: &quot;',@addr,'&quot;,')" />
</xsl:for-each> 

the out put is

   #text": "\"Street1\": \"address1\",\"Street2\": \"address2\",\"Street3\": \"address3\",",

expected output is

"Street1": "GH Nagar" , "Street2": "Naboor" , "Street3": "Besides Al Drive Inn"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM