XSLT 1.0将元素添加到多个匹配项

问题描述

我是XSLT的新手。 我正在尝试将元素添加到从API接收的多个对象中。 所以这是从API接收的XML示例:

<array xmlns="urn:com.sap.b1i.bizprocessor:bizatoms" name="orders">
   <object xmlns="urn:com.sap.b1i.bizprocessor:bizatoms">
      <bunch of info here 1st order>
   </object>
   <object xmlns="urn:com.sap.b1i.bizprocessor:bizatoms">
      <bunch of info here 2nd order>
   </object>
....
</array>

输入是这样的,我需要这样的输出

<array xmlns="urn:com.sap.b1i.bizprocessor:bizatoms" name="orders">
   <object xmlns="urn:com.sap.b1i.bizprocessor:bizatoms">
      <Location>USA</Location>
      <bunch of info here 1st order>
   </object>
   <object xmlns="urn:com.sap.b1i.bizprocessor:bizatoms">
      <Location>USA</Location>
      <bunch of info here 2nd order>
   </object>
....
</array>

这意味着我需要在每个bfa:object中插入一个location元素。

我尝试过这种方法,但没有成功。

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

<xsl:template match="bfa:object">
  <xsl:copy-of select="."/>
  <Location>USA</Location>
</xsl:template>

解决方法

您可以这样做:

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

  <xsl:output method="xml" indent="yes"/>
  
  <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:template>
    
    <xsl:template match="sap:object">
        <xsl:copy>
            <xsl:apply-templates/>
            <xsl:element name="Locations" namespace="urn:com.sap.b1i.bizprocessor:bizatoms">USA</xsl:element>
        </xsl:copy>
    </xsl:template>

  
</xsl:stylesheet>

看到它在这里工作:https://xsltfiddle.liberty-development.net/6pS2B73