将元素与xsi:type属性匹配

时间:2014-12-28 17:16:26

标签: xml xslt

我有一个XML文件,其中包含以下内容:

<contents id="MLC1" name="Requirement1" uri="C:\abc.txt" xsi:type="requirement:Requirement" type="">
<contents id="GO1" name="Goal1" uri="C:\abc.txt" xsi:type="goal:Goal">

我正在尝试匹配XML文件中的所有元素,该文件具有属性xsi:type="requirement:Requirement",以便我可以向其添加名为“label”的新属性。这是我的样式表:

<xsl:template match="//contents[@type='requirement:Requirement']">
    <contents>
        <xsl:attribute name="label">
            <xsl:value-of select="@name"/>
        </xsl:attribute>        
        <xsl:apply-templates select="node()|@*"/>
    </contents>
</xsl:template>

我已经在样式表中声明了xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance",但它似乎无法匹配任何内容。我怀疑是因为原始xml中还有另一个属性“type”,它没有xsi名称空间。有没有人有任何建议我应该用什么来正确匹配这个元素?

2 个答案:

答案 0 :(得分:1)

通常,您需要使用名称空间前缀来正确选择属性:

<xsl:template match="//contents[@xsi:type='requirement:Requirement']">

如果您使用的是模式感知XSLT处理器,xsi:type属性可能具有特殊含义,需要进行相应处理。 See here for more info,但基本上你需要这样做:

<xsl:template match='//contents[@xsi:type = 
     QName("http://requirement/namespace/url/goes/here/", "Requirement")]'>

答案 1 :(得分:1)

首先,使您的输入XML文档格式良好:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <contents id="MLC1" name="Requirement1" uri="C:\abc.txt" 
            xsi:type="requirement:Requirement" type=""/>
  <contents id="GO1" name="Goal1" uri="C:\abc.txt" xsi:type="goal:Goal"/>
</root>

然后,请务必在xsi上使用type名称空间前缀:

<?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:output method="xml" indent="yes" />
  <xsl:template match="//contents[@xsi:type='requirement:Requirement']">
    <contents>
      <xsl:attribute name="label">
        <xsl:value-of select="@name"/>
      </xsl:attribute>        
      <xsl:apply-templates select="node()|@*"/>
    </contents>
  </xsl:template>
</xsl:stylesheet>

然后您将获得以下输出XML:

<?xml version="1.0" encoding="UTF-8"?>
<contents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     label="Requirement1">MLC1Requirement1C:\abc.txtrequirement:Requirement</contents>
相关问题