xslt to add an attribute
I need to add a namespace, and to add an attribute to certain nodes. With this input:
<root>
<Node1>test</Node1>
<DateTo />
</root>
I want this output:
<my:root xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-28T07:33:11">
<my:Node1>test</my:Node1>
<my:DateTo xsi:nil="true"/>
</my:root>
The DateTo node needs to have this attribute set.
I successfully added the namespace with this transform, but cannot get the attribute added.
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:template match='*'>
<xsl:element name='my:{local-name()}' namespace='http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-28T07:33:11' >
<xsl:apply-templates /&g开发者_开发百科t;
</xsl:element>
</xsl:template>
</xsl:stylesheet>"
I get this error "Attribute and namespace nodes cannot be added to the parent element after a text, comment, pi, or sub-element node has already been added." Be grateful for any help here.
You can try the following to insert the additional attribute:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
version='1.0'>
<xsl:template match='*'>
<xsl:element name='my:{local-name()}'
xmlns:my='http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-28T07:33:11'>
<xsl:if test="not(*) and not(normalize-space())">
<xsl:attribute name="xsi:nil">
<xsl:value-of select="true()"/>
</xsl:attribute>
</xsl:if>
<xsl:apply-templates />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
精彩评论