copy an xml to another but changing node attribute and edge attributes
I have an xml with the format
<graph id=1>
<nodes>
<node id =2>
<name value=node1/>
</node>
<node id =3>
<name value=node3/>
</node>
<edges>
<edge id=11 source=2 target=3/>
</edges>
</graph>
Now i want to change the id of node using generate-id() but that should change in all edges too.Eg i change the id of node1 to '1a1' so it should change the source of edge to '1a1' everwhere in xml. It should do this for all nodes and edges.The remaining xml should be as it is.
My xsl
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:tem开发者_JAVA百科plate match="@id[parent::node]">
<xsl:attribute name="id">
<xsl:value-of select="generate-id()"/>
</xsl:attribute>
</xsl:template>
this changes the node id but i want to compare the edges source and target and change them too. The edge source and target are some nodes id .
Any help would be greatly appreciated. Thanks
This stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="kElementById" match="*[@id]" use="@id"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@id">
<xsl:attribute name="id">
<xsl:value-of select="generate-id(..)"/>
</xsl:attribute>
</xsl:template>
<xsl:template match="@source|@target">
<xsl:attribute name="{name()}">
<xsl:value-of select="generate-id(key('kElementById',.))"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
With this well formed input:
<graph id="1">
<nodes>
<node id ="2">
<name value="node1"/>
</node>
<node id ="3">
<name value="node3"/>
</node>
<edges>
<edge id="11" source="2" target="3"/>
</edges>
</nodes>
</graph>
Output:
<graph id="IDAEQBBB">
<nodes>
<node id="IDAHQBBB">
<name value="node1"></name>
</node>
<node id="IDALQBBB">
<name value="node3"></name>
</node>
<edges>
<edge id="IDAQQBBB" source="IDAHQBBB" target="IDALQBBB"></edge>
</edges>
</nodes>
</graph>
Add this section to the XSL that you already have.
<xsl:template match="@source[parent::edge]|@target[parent::edge]">
<xsl:attribute name="{name()}">
<xsl:value-of select="generate-id(//node[@id=current()]/@id)"/>
</xsl:attribute>
</xsl:template>
精彩评论