Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XSLT to copy all elements and attributes with modifications

Status
Not open for further replies.

Jake32

Programmer
Nov 13, 2007
2
CA
I have an xml source that I would like recreate with some modifications. Specifically, I would like to modify attribute values based on a condition. I'm able to recreate the XML file but it's the modifications that I'm having difficulties with.

For example, based on the xml sample below, if PARA Style = "Section_Title", I would like to:

1) Change the value for the align attribute from "left" to "right" and
2) Change the text from "This is My Title" to "Book Title"

Any help would be greatly appreciated.


My XML file is as follows...

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<MYROOT>

<BODY>
<SECTION>
<PARA Style="Section_Title" align="left" emphasis-bold="true">This is My Title </PARA>

<PARA Style="Body" align="left">
<STEXT font="Arial" hidden="true">This is some special text</STEXT>
<LINK Style="Body Text" align="left"> </PARA>
</SECTION>
</BODY>
</MYROOT>


So far I'm only able to recreate the same XML file using the following XSL

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="*|text()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="@*">
<xsl:copy>
<xsl:value-of select="."/>
</xsl:copy>
</xsl:template>


Thanks.
 
Thanks Tom for your help.

I do understand how to copy all elements and text nodes and how to rename an attribute's name as in the example provided.

However, I'm focusing more on changing the attribute's value.

So building on the example provided, I would like to achieve the following...

if <foobar c="a"/> and <barfoo c="b"/>

then output

<foobar c="y"/>
<barfoo c="z"/>

Any thoughts on how this can be done?

 
Yes, use the <xsl:attribute> element in the template that matches the c attribute, along the lines of:
Code:
<xsl:template match="foobar/@c">
   <xsl:attribute name="c">
   <xsl:text>y</xsl:text>
   </xsl:attribute> 
</xsl:template>
<xsl:template match="barfoo/@c">
   <xsl:attribute name="c">
   <xsl:text>z</xsl:text>
   </xsl:attribute> 
</xsl:template>
[small]Warning: typed, not tested[/small]

Since I am not aware of what your actual transformation rules might be, all I can provide is this hint.




Tom Morrison
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top