Change an attribute of an XML element

0

I have the following XML:

<?xml version="1.0" encoding="WINDOWS-1252"?>
  -<NewDataSet>
    -<xs:schema xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="" id="NewDataSet">
      -<xs:element msdata:Locale="" msdata:MainDataTable="INFO" msdata:IsDataSet="true" name="NewDataSet">
        -<xs:complexType>
          -<xs:choice maxOccurs="unbounded" minOccurs="0">
            -<xs:element msdata:Locale="" name="INFO">

I need to change the last line with XSLT where it reads name="INFO" get name="INFO2" . I have tried several transformations and none works: (

    
asked by anonymous 09.03.2017 / 16:26

1 answer

0

To replace the value of an attribute it is necessary to first locate its element through an XPath expression, which will be passed to the stylesheet template.

I'll assume that the selection is made by the name of the xs:element external that has a name attribute with the value of NewDataSet . In this case, the XPath to find this element is:

//xs:element[@name='NewDataSet']

This can be passed to the match attribute of xsl:template without // and will be the context used within the template. You can also use a more specific context by continuing the path to the element where the attribute you want to change is

xs:element[@name='NewDataSet']/xs:complexType/xs:choice/xs:element

Knowing the element you want to change, you then need to define two templates in the style sheet. One to copy all other elements and attributes, and one to select the element above and change its attribute. You must also declare the namespaces you are using, so that the qualified XPath expressions above work.

The XSLT below does the replacement using the criteria described above:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
    version="1.0">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>

    <xsl:template match="*|@*">
        <xsl:copy>
            <xsl:apply-templates select="*|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="xs:element[@name='NewDataSet']/xs:complexType/xs:choice/xs:element">
        <xsl:copy>
            <xsl:attribute name="name">INFO2</xsl:attribute>
            <xsl:apply-templates select="@*[name() != 'name']|*"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

The first template copies all elements and attributes to the output. The second replaces the value of the attribute and copies the subelements and other attributes of xs:element if they exist.

    
09.03.2017 / 21:52