简体   繁体   English

使用XSLT修改XML文件中的属性

[英]Modifying attributes in an XML file with XSLT

I want to modify an XML file, I have some attributes in this XML file and I want to change this ie if the producer is VW, then Iwant to change the country to "Germany" hier is my XML: 我想修改一个XML文件,在这个XML文件中有一些属性,我想更改它,即如果生产者是大众,那么我想将国家/地区更改为“德国”,这就是我的XML:

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="example.xslt"?>
<Auto>
  <lkw producer="VW" country="USA">
    <name>Polo</name>
    <price>$5955.2</price>
    <color>red</color>
  </lkw>
  <lkw producer="Audi" country="germany">
    <name>A8</name>
    <price>$8955.2</price>
    <color>black</color>
  </lkw>
  <lkw producer="BMW" country="USA">
    <name>Polo</name>
    <price>$6955.2</price>
    <color>blue</color>
  </lkw>
 <lkw producer="VW" country="China">
    <name>Pasat</name>
    <price>$2955.2</price>
    <color>red</color>
  </lkw>
</Auto>

and this is my XSLT: 这是我的XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@producer[parent::VW]">
    <xsl:attribute name="country">
      <xsl:value-of select="'germany'"/>
    </xsl:attribute>
  </xsl:template>
</xsl:stylesheet>

but I see no change in my XML file, Could you please tell me, Where is my mistake in XSLT? 但是我的XML文件没有任何变化,请您告诉我,我在XSLT中的错误在哪里?

Looking at your current template... 查看您当前的模板...

<xsl:template match="@producer[parent::VW]">

This is actually equivalent to this... 这实际上等效于此...

<xsl:template match="VW/@producer">

So, it is looking for an element called VW , when you really want to be checking the value of the attribute. 因此,当您确实要检查属性值时,它正在寻找一个称为VW的元素。

What you are really trying to do, is match the @country attribute for elements which have an @producer attribute equal to VW 你真正要做的,是匹配其具有@producer属性等于VW元素@country属性

<xsl:template match="lkw[@producer='VW']/@country">
  <xsl:attribute name="country">
    <xsl:value-of select="'germany'"/>
  </xsl:attribute>
</xsl:template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM