Xml 获取当前节点号的XSLT/XPath
我有以下要转换的xml数据结构:Xml 获取当前节点号的XSLT/XPath,xml,xslt,xpath,Xml,Xslt,Xpath,我有以下要转换的xml数据结构: <root> <main1> <text-body> <title>A</title> <subtitle>A</subtitle> </text-body> <!-- other stuff --> &
<root>
<main1>
<text-body>
<title>A</title>
<subtitle>A</subtitle>
</text-body>
<!-- other stuff -->
<text-body>
<titel>Aa</titel>
<subtitel>Aa</subtitel>
</text-body>
<!-- other stuff -->
<text-body>
<titel>Aaa</titel>
<subtitel>Aaa</subtitel>
</text-body>
</main1>
<main2>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main2>
</root>
A.
A.
Aa
Aa
Aaa
Aaa
B
B
B
C
C
C
D
D
D
我需要将main/text body中的数据替换为main2/text body中的数据,但将其他内容保留在main1中。输出应如下所示:
<root>
<main1>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<!-- other stuff -->
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<!-- other stuff -->
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main1>
<main2>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main2>
</root>
B
B
B
C
C
C
D
D
D
B
B
B
C
C
C
D
D
D
我有以下xsl代码:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="main1/text-body">
<xsl:param name="count" select="count(preceding-sibling::node())"/>
<xsl:copy-of select="/root/main2/text-body[$count]"/>
</xsl:template>
</xsl:stylesheet>
我尝试获取main1/text body的当前节点索引,以填充main2的右侧文本体。但它不起作用。以下是电流输出:
<?xml version="1.0" encoding="UTF-8"?><root>
<main1>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<!-- other stuff -->
<!-- other stuff -->
</main1>
<main2>
<text-body>
<title>B</title>
<subtitle>B</subtitle>
<body>B</body>
</text-body>
<text-body>
<title>C</title>
<subtitle>C</subtitle>
<body>C</body>
</text-body>
<text-body>
<title>D</title>
<subtitle>D</subtitle>
<body>D</body>
</text-body>
</main2>
</root>
B
B
B
B
B
B
C
C
C
D
D
D
请帮忙 XPath和XSLT是基于1的索引。为了选择第一项,谓词筛选器将查找
[1]
,而不是[0]
因此,变量$count
需要将1
添加到前面同级选择的count()
。此外,您应该计算前面同级的文本体
元素,而不是所有/任何节点()
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="main1/text-body">
<xsl:param name="count" select="count(preceding-sibling::text-body)+1"/>
<xsl:copy-of select="/root/main2/text-body[$count]"/>
</xsl:template>
</xsl:stylesheet>