如何使用XSLT更新XML中的单个值?

时间:2012-03-16 22:10:03

标签: xml xslt

我有一个巨大的XML文件,我想在其中更新单个值。有没有办法编写一个XSLT文件,它可以通过简单的更改生成现有XML文件的精确副本?

例如,假设我有以下XML,并且我想将员工Martin的职位编号更改为100.我该怎么办?

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <!-- ... -->

  <Employee name="Martin">
    <Position number="50" />
  </Employee>

    <!-- ... -->
</Employees>

3 个答案:

答案 0 :(得分:5)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

    <!--Identity template that will copy every
        attribute, element, comment, and processing instruction
        to the output-->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--more specific template match on @number that will 
        change the value to 100-->
    <xsl:template match="Employee[@name='Martin']/Position/@number">
        <xsl:attribute name="number">100</xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:4)

从身份模板开始

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

为您的更改添加一个模板

<xsl:template match="Employee[@name='Martin']/Position">
 <Position number="100" />
</xsl:template>

答案 2 :(得分:-1)

<xsl:template match="/Employees/Employee/Position">
  <xsl:attribute name="number">100</xsl:attribute>
</xsl:template>
相关问题