你能帮我使用XSLT映射将下面的HTML转换为XML吗?
输入网页:
<html><head></head><body>Array
(
[Value] => 123
[Head] => 456
[Description] => Array
(
[1] => ABC
[2] => DEF
[3] => GHI
)
[Price] => Array
(
[1] => 123
[2] => 456
[3] => 789
)
[Quantity] => Array
(
[1] =>
[2] =>
[3] =>
)
)</body></html>
输入网页
预期的 XML:
<?xml version="1.0" encoding="UTF-8"?>
<aa>
<Value>123</Value>
<Head>456</Head>
<Lines>
<Description>ABC</Description>
<Price>123</Price>
<Quantity></Quantity>
</Lines>
<Lines>
<Description>DEF</Description>
<Price>456</Price>
<Quantity></Quantity>
</Lines>
<Lines>
<Description>GHI</Description>
<Price>789</Price>
<Quantity></Quantity>
</Lines>
</aa>
输出 XML
值和头只会出现一次。而值、描述和数量的数组可能是多个。我需要在标签内对所有 1 、2 等进行分组。请帮忙。
您可以在 XSLT 2.0 中使用以下代码:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="//body"/>
</xsl:template>
<xsl:template match="body">
<xsl:variable name="temp">
<xsl:analyze-string select="text()" regex="[(.+)] => (.*)">
<xsl:matching-substring>
<xsl:choose>
<xsl:when test="matches(regex-group(1), '^[0-9]+$')">
<Array name="{regex-group(1)}"><xsl:value-of select="regex-group(2)"/></Array>
</xsl:when>
<xsl:otherwise>
<xsl:element name="{regex-group(1)}"><xsl:value-of select="regex-group(2)"/></xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:variable>
<aa>
<xsl:copy-of select="$temp//Value"/>
<xsl:copy-of select="$temp//Head"/>
<xsl:for-each-group select="$temp//Array" group-by="@name">
<Lines>
<Description><xsl:value-of select="current-group()[1]"/></Description>
<Price><xsl:value-of select="current-group()[2]"/></Price>
<Quantity><xsl:value-of select="current-group()[3]"/></Quantity>
</Lines>
</xsl:for-each-group>
</aa>
</xsl:template>
</xsl:stylesheet>
输出
<?xml version="1.0" encoding="UTF-8"?>
<aa>
<Value>123</Value>
<Head>456</Head>
<Lines>
<Description>ABC</Description>
<Price>123</Price>
<Quantity/>
</Lines>
<Lines>
<Description>DEF</Description>
<Price>456</Price>
<Quantity/>
</Lines>
<Lines>
<Description>GHI</Description>
<Price>789</Price>
<Quantity/>
</Lines>
</aa>