On 07/12/2012 09:53 AM, stuart shepherd wrote: > Searching the web I've seen some examples in XSLT on how to > do something like this, but I have never used XSLT. Does anyone know if > there is a way to do this in XML.
XSLT is your best bet. Here's a sample stylesheet which will: - change the name of all elements named 'old' to 'new' - change the name of all elements with an attribute named 'old' to 'new' ---- BEGIN stylesheet ---- <?xml version="1.0" standalone="yes"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml"/> <!-- Template matches every node and attribute--> <xsl:template match="node()|@*"> <xsl:choose> <!-- if name of element is 'old' or element contains an attribute named 'old', replace it with 'new' --> <xsl:when test="@old or name(.)='old'"> <xsl:variable name="old_node" select="node()"/> <xsl:variable name="old_value" select="./text()"/> <xsl:variable name="attributes" select="@*"/> <xsl:variable name="children" select="./*"/> <!-- create a 'new' element with attributes and children from the 'old' node, with its old value --> <xsl:element name="new"> <xsl:copy-of select="$attributes|$children"/> <xsl:value-of select="$old_value"/> </xsl:element> </xsl:when> <!-- else, just copy the node/attributes --> <xsl:otherwise> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ---- END stylesheet ---- Sample XML: <?xml version="1.0" standalone="yes"?> <swap> <old attr="attr1">This used to be inside the old node <old_child1>This is old_child1</old_child1> </old> <foo attr="attr2">This is just a middle element...</foo> <foo old="old attribute"/> </swap> Output of stylesheet processing using xsltproc (libxml 20708, libxslt 10126 and libexslt 815): $ xsltproc swap.xsl swap.xml <?xml version="1.0"?> <swap> <new attr="attr1"><old_child1>This is old_child1</old_child1>This used to be inside the old node </new> <foo attr="attr2">This is just a middle element...</foo> <new old="old attribute"/> </swap> You can modify the attribute match criteria (@old) to actually evaluate its contents ([@old='old_parent']), etc... Hope this helps. Piotr _______________________________________________ xml mailing list, project page http://xmlsoft.org/ [email protected] https://mail.gnome.org/mailman/listinfo/xml
