1

输入 XML:

.....
..... <!-- Many lines of code -->
.....
<Attribute Name="Attr1">  
  <Array>
       <Object Type="Object1">
          <Attribute Name="Attr2">
              "123"
              "234"
           </Attribute>
           <Attribute Name="Attr3">"456"</Attribute>
        </Object>
        <Object Type="Object2">
           <Attribute Name="Attr4">
               "444"
               "555"
            </Attribute>               
         </Object>
         <Object Type="Object3">
            <Attribute Name="Attr5">
                "666"   
                "777"
                "888"     
    <!-- My new item should come here -->   
             </Attribute>
          </Object> 
   </Array>
</Attribute>

我尝试使用以下 XSLT 将新条目 (999) 添加到上述位置“我的新项目应该来这里”。在插入这个新项目之前,我想检查节点Attribute(<Attribute Name = "Attr5")是否具有值“888”。只有当它包含 "888" 时,我才应该在之后插入 "999" 。你能告诉我这是怎么做到的吗?

    <?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:output method="xml" indent="yes"/>

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

     <xsl:variable name="obj" select='"Object3"'/>
     <xsl:variable name="attr" select='"Attr5"'/>
     <xsl:param name="evalue">"999"</xsl:param>

     <xsl:template match="Attribute/Array/Object[@Type=$obj]/Attribute[@Name=$attr]">
      <xsl:copy>
    <xsl:copy-of select="@*" />
    <xsl:value-of select="." />
    <xsl:value-of select="$evalue"/>
  </xsl:copy>
     </xsl:template>
    </xsl:stylesheet>

输出 XML

<Attribute Name="Attr1">  
  <Array>
       <Object Type="Object1">
          <Attribute Name="Attr2">
              "123"
              "234"
           </Attribute>
           <Attribute Name="Attr3">"456"</Attribute>
        </Object>
        <Object Type="Object2">
           <Attribute Name="Attr4">
               "444"
               "555"
            </Attribute>               
         </Object>
         <Object Type="Object3">
            <Attribute Name="Attr5">
                "666"   
                "777"
                "888"     
                "999"
             </Attribute>
          </Object> 
   </Array>
</Attribute>

这就是最终 XML 的样子。请帮帮我

4

1 回答 1

2

它在您的模板中缺少许多说明...

<xsl:template match="Attribute/Array/Object[@Type=$obj]/Attribute[@Name=$attr and contains(., '&quot;888&quot;')]">
  <xsl:copy>
    <xsl:copy-of select="@*" />
    <xsl:value-of select="." />
    <xsl:value-of select="$evalue"/>
  </xsl:copy>
</xsl:template>
于 2013-11-07T09:00:05.640 回答