如何使用XSLT在XML节点中添加和删除项目

时间:2018-10-18 11:16:52

标签: xml xslt

<html>

<head>
</head>

<body>
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
  <span>7</span>
  <span>8</span>
</body>

</html>

在上面的xml中,我必须首先删除document节点中的所有项目,以便获得以下输出。

<?xml version="1.0" encoding="UTF-8"?>
<partner id="A12345">
   <classes>
      <class id="101"
            <documents>
                <document isWaived="true" name="Doc 1">true</document>
                <document isWaived="false" name="Doc 2">false</document>
            </documents>
        </class>
    </classes>
</partner>

并且想要添加一组新文档以获得以下输出。

<?xml version="1.0" encoding="UTF-8"?>
<partner id="A12345">
   <classes>
      <class id="101"
            <documents>
            </documents>
        </class>
    </classes>
</partner>

我当前使用以下xsl删除文档节点中的内容。

<?xml version="1.0" encoding="UTF-8"?>
<partner id="A12345">
   <classes>
      <class id="101"
            <documents>
                <document isWaived="false" name="Doc 3">false</document>
            </documents>
        </class>
    </classes>
</partner>

但这给出了这样的输出

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

<xsl:template match="document" />

现在,我必须向节点数组添加一些项目。我们应该怎么做。 任何人都可以帮助删除节点的内容并添加新值。

1 个答案:

答案 0 :(得分:0)

由于您希望输出为静态,因此只需更改文档模板,如:

<xsl:template match="documents">
    <xsl:copy>
        <document isWaived="false" name="Doc 3">false</document>
    </xsl:copy>
</xsl:template>

考虑到您正在搜索tokenize()函数的评论。

<xsl:for-each select="tokenize($documentstring,';')"> <!-- the second argument is the character you want to split the string on -->
     <document isWaived="false" name="{.}"> 
         <!-- The braces allow you to run codesegments inside the attribute -->
     </document>
</xsl:for-each>