IP地址格式化

时间:2014-03-13 18:20:47

标签: xml xslt

是否有格式化IP地址的XSLT解决方案 我想要的是如下 066087031091 => 66.87.31.91

应删除左边的填充零并将整个字符串拆分为4并插入点。

1 个答案:

答案 0 :(得分:1)

如果非结构化IP地址每次包含12个数字,您可以使用XSLT 1.0中的命名模板对其进行格式化

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <!-- Premise: non-formated IP address consist of 12 number everytime -->
    <xsl:variable name="ip" select="'066087031091'" />

    <xsl:template match="/">
        <xsl:call-template name="formatIp">
            <xsl:with-param name="ip" select="$ip" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="formatIp">
        <xsl:param name="ip" />
        <!-- substring - takes 3 characters from position 1 -->
        <!-- number() function - removes leading zerou -->
        <xsl:value-of select="number(substring($ip, 1, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 4, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 7, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 10, 3))" />
    </xsl:template>

</xsl:stylesheet>

或在XSLT 2.0中使用用户功能

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:my="my-functions">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

        <xsl:variable name="ip" select="'066087031091'" />

    <xsl:template match="/">
        <xsl:value-of select="my:formatIp($ip)" />
    </xsl:template>

    <xsl:function name="my:formatIp">
        <xsl:param name="ip" />
        <!-- substring - takes 3 characters from position 1 -->
        <!-- number() function - removes leading zerou -->
        <xsl:value-of select="number(substring($ip, 1, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 4, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 7, 3))" />
        <xsl:text>.</xsl:text>
        <xsl:value-of select="number(substring($ip, 10, 3))" />
    </xsl:function>

</xsl:stylesheet>

正则表达式也可用于XSLT 2.0,但以前的解决方案应该足够了。