我对 XSLT 很陌生,这是我的 XML:
<projects>
<project>
<number>1</number>
<title>Project X</title>
</project>
<project>
<number>2</number>
<title>Project Y</title>
</project>
<project>
<number>3</number>
<title>Project Z</title>
</project>
</projects>
如果我有一个项目并且想要获得紧随其后的同级项目,我该怎么做?
这段代码似乎对我不起作用:
/projects[title="Project X"]/following-sibling
最佳答案
这实际上完全是一个 XPath 问题。
使用:
/*/project[title = 'Project X']/following-sibling::project[1]
这将选择作为 XML 文档中顶级元素的子元素的任何 Project
元素的任何第一个后续兄弟 Project
以及至少一个的字符串值它的 title
child 是字符串 "Project X"
。
基于 XSLT 的验证:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select=
"/*/project[title = 'Project X']/following-sibling::project[1]"/>
</xsl:template>
</xsl:stylesheet>
当此转换应用于提供的 XML 文档时:
<projects>
<project>
<number>1</number>
<title>Project X</title>
</project>
<project>
<number>2</number>
<title>Project Y</title>
</project>
<project>
<number>3</number>
<title>Project Z</title>
</project>
</projects>
计算 XPath 表达式并将正确选择的元素复制到输出:
<project>
<number>2</number>
<title>Project Y</title>
</project>
关于xml - 如何在 XSLT 中获取以下同级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10246371/