[英]Check if XML has two different types of element node how to bring it in output XML using XSLT
I already have an input XML 我已经有输入XML
<tutorial>
<lessons>
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
</lessons>
</tutorial>
The output should be 输出应为
<Geography>
<historical>
<social>
<toc1>
<toc>
<chapter>
chapter1
<chapter>
<unit>
unit 1
</unit>
<pages>
page1
</pages>
</toc>
</toc1>
<social>
</historical>
actually i am getting confused here 其实我在这里很困惑
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
here i need two outpus 在这里我需要两个输出
for the first lesson i need it as above output 对于第一堂课,我需要上面的输出
for the second lesson i need it as output like below 对于第二课,我需要它作为如下输出
<historical>
<social>
<toc1>
<toc>
<unit>
unit 1
</unit>
<toc>
</toc1>
<social>
</historical>
but sometimes i will get both type in xml i am totally confused how to do this. 但是有时我会同时在xml中输入这两种类型,我对此完全感到困惑。
can any one guide me here it can be in both XSLT1.0 and XSLT2.0 有人可以在这里指导我吗?它可以同时存在于XSLT1.0和XSLT2.0中
Regards Karthic 关于Karthic
This XSLT 2.0 transformation : 此XSLT 2.0转换 :
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vNames" select="'chapter', 'unit', 'pages'"/>
<xsl:template match="lessons">
<Geography>
<historical>
<social>
<toc1>
<xsl:apply-templates/>
</toc1>
</social>
</historical>
</Geography>
</xsl:template>
<xsl:template match="lesson[matches(., '(chapter\s*\d+)?\s+(unit\s*\d+)\s+(page\s*\d+)?')]">
<xsl:analyze-string select="."
regex="(chapter\s*\d+)?\s+(unit\s*\d+)\s+(page\s*\d+)?">
<xsl:matching-substring>
<toc>
<xsl:for-each select="1 to 3">
<xsl:if test="regex-group(current())">
<xsl:element name="{$vNames[current()]}">
<xsl:sequence select="regex-group(current())"/>
</xsl:element>
</xsl:if>
</xsl:for-each>
</toc>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document: 当应用于提供的XML文档时:
<tutorial>
<lessons>
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
</lessons>
</tutorial>
produces the wanted, correct result: 产生想要的正确结果:
<Geography>
<historical>
<social>
<toc1>
<toc>
<chapter>chapter1</chapter>
<unit>unit 1</unit>
<pages>page1</pages>
</toc>
<toc>
<unit>unit 1</unit>
</toc>
</toc1>
</social>
</historical>
</Geography>
Explanation : 说明 :
Proper use of XSLT 2.0 Regular expression capabilities such as: 正确使用XSLT 2.0正则表达式功能,例如:
The <xsl:analyze-string>
and <xsl:matching-substring>
instrunctions. <xsl:analyze-string>
和<xsl:matching-substring>
指令。
The regex-group()
function. regex-group()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.