Vallabh Lakade
Vallabh Lakade

Reputation: 832

XML to XSL transformation

I am new to XML. I am trying to convert the following XMl file

 <?xml version="1.0"?>
    <parent original_id="OI123" id="I123">
        <custompanel panel="cp"></custompanel>
    </parent>

into the following HTML

<html>
    <body><div xmlAttribute="{"original-id":"OI123","id":"I123"}">
               <p xmlAttribute={"panel":"cp"}/>
          </div>
    </body>
</html>

XML tag <parent> should be converted to <div> and <custompanel> should be converted to <p> tag.

I have read the XSTL documentation from W3CSchool but still I am not exactly sure how to approach the problem.Can anyone help me with it? The custom attribute needs to be stored in xmlAttribute as JSONObject.

Upvotes: 1

Views: 124

Answers (1)

simbabque
simbabque

Reputation: 54323

After a quick research of the correct syntax I came up with this.

<?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"
    doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
    indent="yes"
    encoding="utf-8" />
    <xsl:template match="parent">
        <html>
            <body>
                <div xmlAttribute="{{'original-id':'{@original_id}','id':'{@id}'}}">
                    <xsl:apply-templates />
                </div>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="custompanel">
        <p xmlAttribute="{{'panel':'{@panel}'}}" />
    </xsl:template>
</xsl:stylesheet>

The tricky part is espacing the {} for the JSON, which we build ourselves. You need two curly braces {{ to have a literal one. Also you need to use single quotes ' inside the attributes as double quotes would be escaped to &quot;. You can access attributes with the @foo selector, but now you need to use actual {} to make the processor recognize it should do something.

I guess that your actual file has more than one <parent>. In that case you need to have a root element around it, and you need to adjust the XSLT. Add another <xsl:template match="/"> and move the HTML frame there.

Upvotes: 1

Related Questions