简体   繁体   English

如何使用XSL从XML元素获取信息

[英]How to get information from XML element using XSL

<start>
    <tag> dog=German shepherd|cat=has a lot of spots </tag>
</start>
<start>
    <tag> cat=black cat|dog=Clifford </tag>
</start>

Suppose I had an XML document like this and wanted to loop through it and select the value of cat and dog and print them separately using XSL how should I go about doing so? 假设我有一个像这样的XML文档,并且想遍历它,选择cat和dog的值,然后使用XSL分别打印它们,我应该怎么做?

Given a well-formed input XML, such as: 给定格式正确的输入XML,例如:

<root>
    <start>
        <tag> dog=German shepherd|cat=has a lot of spots </tag>
    </start>
    <start>
        <tag> cat=black cat|dog=Clifford </tag>
    </start>
</root>

and an XSLT 2.0 processor, you could apply the following stylesheet: 和XSLT 2.0处理器,您可以应用以下样式表:

XSLT 2.0 XSLT 2.0

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/root">
    <xsl:copy>
        <xsl:for-each select="start/tokenize(tag, '\|')">
            <entry>
                <key>
                    <xsl:value-of select="substring-before(., '=')" />
                </key>
                <value>
                    <xsl:value-of select="substring-after(., '=')" />
                </value>
            </entry>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

to receive: 接受:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <entry>
      <key> dog</key>
      <value>German shepherd</value>
   </entry>
   <entry>
      <key>cat</key>
      <value>has a lot of spots </value>
   </entry>
   <entry>
      <key> cat</key>
      <value>black cat</value>
   </entry>
   <entry>
      <key>dog</key>
      <value>Clifford </value>
   </entry>
</root>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM