使用变量作为属性值通过 XSLT 将新元素集添加到现有 XML 文件

Add new element set to existing XML files via XSLT using variables as attribute values

我不太习惯使用 XSLT,但我想向现有的 XML 文件添加一些新元素,如下所示:

    <TEI>
     <teiHeader>
      ...
      <profileDesc/>
      ...
     </teiHeader>
    ...
     <body/>
    </TEI>

我要添加的是这个(到 profileDesc):

        <tei:particDesc>
            <tei:listPerson>
                <tei:person role="" ref="{$persons}">
                    <tei:persName></tei:persName>
                </tei:person>
            </tei:listPerson>
            <tei:listOrg>
                <tei:org role="" ref="{$institutions}">
                    <tei:orgName></tei:orgName>
                </tei:org>
            </tei:listOrg>
        </tei:particDesc>

所以我想添加 particDesc 元素并将 $persons 和 $institutions 的不同值添加到 ref 属性。

我的 XSLT 如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tei="http://www.tei-c.org/ns/1.0"
    exclude-result-prefixes="xs"
    version="1.0">

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

<xsl:template match="tei:profileDesc">
        <xsl:variable name="persons" select=".//body//rs[@type='person'][not(.=preceding::*)]"/>
        <xsl:variable name="institutions" select=".//body//rs[@type='institution'][not(.=preceding::*)]"/>
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
            <tei:particDesc>
                <tei:listPerson>
                    <tei:person role="" ref="{$persons}">
                        <tei:persName></tei:persName>
                    </tei:person>
                </tei:listPerson>
                <tei:listOrg>
                    <tei:org role="" ref="{$institutions}">
                        <tei:orgName></tei:orgName>
                    </tei:org>
                </tei:listOrg>
            </tei:particDesc>
        </xsl:copy>
    </xsl:template>
    
</xsl:stylesheet>

当前输出:

<tei:particDesc xmlns:tei="http://www.tei-c.org/ns/1.0"><tei:listPerson><tei:person role="" ref=""><tei:persName/></tei:person></tei:listPerson><tei:listOrg><tei:org role="" ref=""><tei:orgName/></tei:org></tei:listOrg></tei:particDesc></profileDesc>

期望的输出:

<particDesc>
 <listPerson>
  <person role="" ref="[value of distinct persons-value 1]">
   <persName></persName>
  </person>
  <person role="" ref="[value of distinct persons-value 2]">
   <persName></persName>
  </person>
  ...
 </listPerson>
 <listOrg>
  <org role="" ref="[value of distinct institutions-value 1]">
   <orgName></orgName>
  </org>
  <org role="" ref="[value of distinct institutions-value 2]">
   <orgName></orgName>
  </org>
  ...
 </listOrg>
</particDesc>

提前致谢!

您输入的 <profileDesc/> 元素为空,因此 .//body 未选择任何内容。也许您的意思是 select="//body",或 select="../../body",或者如 Martin 所建议的,select="../../tei:body".