2

我想知道是否有人知道是否有一种简单的方法可以将我的 xml 文件中的所有字符串更改为数组?

例子:

//This is the string I need to change:
<string name="sample1">value1, value2, value3, value4, value5</string>
//This is the way I need it to be:
<array name="sample1">
    <item>value1</item>
    <item>value2</item>
    <item>value3</item>
    <item>value4</item>
    <item>value5</item>
</array>

我的问题不是我不知道如何手动完成。但我正在寻找一种更容易模拟这个过程的方法,因为我有 120 个字符串,每个字符串有 25-90 个值。

一个很好的例子是通过单击转换多个图像扩展,使用 GIMP 的附加组件为您模拟每个图像的该过程。

任何了解我所问内容的人都会知道一种将字符串转换为数组的方法吗?

4

2 回答 2

3

这个 XSLT:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <array>
        <xsl:attribute name="name">
            <xsl:value-of select="string/@name"/>
        </xsl:attribute>
        <xsl:apply-templates/>
    </array>
</xsl:template>

<xsl:template match="string/text()" name="tokenize">
    <xsl:param name="text" select="."/>
    <xsl:param name="sep" select="','"/>
    <xsl:choose>
        <xsl:when test="not(contains($text, $sep))">
            <item>
                <xsl:value-of select="normalize-space($text)"/>
            </item>
        </xsl:when>
        <xsl:otherwise>
            <item>
                <xsl:value-of select="normalize-space(substring-before($text, $sep))"/>
            </item>
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $sep)"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>
</xsl:stylesheet>

应用于此 XML:

<?xml version="1.0" encoding="UTF-8"?>
<string name="sample1">value1, value2, value3, value4, value5</string>

给出这个输出:

<?xml version="1.0" encoding="UTF-8"?>
<array name="sample1">
<item>value1</item>
<item>value2</item>
<item>value3</item>
<item>value4</item>
<item>value5</item>
</array>

XSLT 使用递归模板遍历您的字符串值并以逗号分隔它们。

于 2012-08-23T06:28:03.647 回答
1

这可以使用 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:template match="/*">
  <array name="{@name}">
     <xsl:for-each select="tokenize(., ',\s*')">
      <item><xsl:value-of select="."/></item>
     </xsl:for-each>
    </array>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的 XML 文档时:

<string name="sample1">value1, value2, value3, value4, value5</string>

产生了想要的正确结果

<array name="sample1">
   <item>value1</item>
   <item>value2</item>
   <item>value3</item>
   <item>value4</item>
   <item>value5</item>
</array>
于 2012-08-23T12:40:00.723 回答