如何使用XSLT解析SOAP信封内的CSV内容?

时间:2014-04-23 14:28:02

标签: xml xslt csv soap

我有一个SOAP信封:

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <text xmlns="http://ws.apache.org/commons/ns/payload">
      +++++REC START+++++
      1,Mr Egg Sample,
      +++++REC END+++++
      +++++REC START+++++
      2,Mr Other Egg Sample,
      4,Mr A N Other Egg Sample,
      +++++REC END+++++
    </text>
  </soapenv:Body>
</soapenv:Envelope>

我必须将其转换为以下内容

<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <ex:ample xmlns:ex="http://example.org">
      1,Mr Egg Sample,
    </ex:ample>

    <ex:ample xmlns:ex="http://example.org">
      2,Mr Other Egg Sample,
      4,Mr A N Other Egg Sample,
    </ex:ample>
  </soapenv:Body>
</soapenv:Envelope>

我查看过许多与CSV相关的XSLT示例,例如thisthis,但我没有使用XSLT从中获得解决方案的专业知识。我希望我有时间自己解决这个问题,但事实并非如此。任何人都可以为我的问题提供XSLT解决方案吗?

1 个答案:

答案 0 :(得分:0)

在XSLT 2.0中,您可以使用 xsl:analyze-string 来使正则表达式与文本匹配。

 <xsl:analyze-string select="." regex="\+\+\+\+\+REC START\+\+\+\+\+([\s\S]*?)\+\+\+\+\+REC END\+\+\+\+\+">

请注意在表达式中使用捕获组。然后,您可以使用 regex-group 函数来获取匹配的文字:

        <xsl:matching-substring>
            <ex>
                <xsl:value-of select="regex-group(1)" />
            </ex>
        </xsl:matching-substring>

试试这个XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output indent="yes"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*:text">
        <xsl:analyze-string select="." regex="\+\+\+\+\+REC START\+\+\+\+\+([\s\S]*?)\+\+\+\+\+REC END\+\+\+\+\+">
            <xsl:matching-substring>
                <ex>
                    <xsl:value-of select="regex-group(1)" />
                </ex>
            </xsl:matching-substring>
        </xsl:analyze-string>
    </xsl:template>
</xsl:stylesheet>

(注意,我没有在这里打扰使用命名空间创建的元素,但我相信你可以解决这个问题)

相关问题