2010-08-26 62 views
2

我对XSLT一无所知,但我需要一次性的东西。这应该很简单。 XSLT需要做什么才能进行如下所示的以​​下输入和显示。需要帮助使用XSLT从XML输出文本节点

INPUT:

<TestResult> 
<set-value idref="account_lockout_duration_var">900</set-value> 
<set-value idref="account_lockout_threshold_var">5</set-value> 
    <group> 
     <id>345</id> 
     <id>265</id> 
     <field>true</field> 
     <message>dont do that</message> 
    </group> 
    <group> 
     <id>333</id> 
     <field>false</field> 
    </group> 
</TestResult> 

OUTPUT

345,265,true 
333,false 

这仅仅是一个代码段,只能有每组一个磁场元件,但ID元件是未结合的。

我修改了输入,使用下面的答案,我得到额外的输出(一切都是输出,当我只想要ID和域元素 感谢

回答

2

我会做这样的事情:

XML:

<TestResult> 
    <set-value idref="account_lockout_duration_var">900</set-value> 
    <set-value idref="account_lockout_threshold_var">5</set-value> 
    <group> 
    <id>345</id> 
    <id>265</id> 
    <field>true</field> 
    <message>dont do that</message> 
    </group> 
    <group> 
    <id>333</id> 
    <field>false</field> 
    </group> 
</TestResult> 

XSL:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text"/> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="node()|@*"> 
    <xsl:apply-templates/> 
    </xsl:template> 

    <xsl:template match="/TestResult/group"> 
    <xsl:apply-templates/> 
    <xsl:if test="following-sibling::group"> 
     <xsl:text>&#xA;</xsl:text> 
    </xsl:if> 
    </xsl:template> 

    <xsl:template match="/TestResult/group/id|field"> 
    <xsl:value-of select="."/> 
    <xsl:if test="following-sibling::id or following-sibling::field">,</xsl:if> 
    </xsl:template> 

</xsl:stylesheet> 

OUT:

345,265,true 
333,false 
+0

谢谢,看我的编辑。 – user318747 2010-08-26 16:17:56

+0

我更新了我的答案以供您修改。 – 2010-08-26 16:27:39

+0

我认为你的规则'xsl:template match =“node()| @ *”'并不是真的需要。查看我的答案以获得更简洁的代码。 – 2010-08-26 19:32:45

1

这将是这样的:。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes"/> 
    <xsl:template match="/"> 
    <xsl:apply-templates/> 
    </xsl:template> 
    <xsl:template match="group"> 
    <xsl:apply-templates/> 
    </xsl:template> 
    <xsl:template match="id"> 
    <xsl:apply-templates/> 
    <xsl:text>;</xsl:text> 
    </xsl:template> 
    <xsl:template match="field"> 
    <xsl:apply-templates/> 
    <xsl:text> 
</xsl:text> 
    </xsl:template> 
</xsl:stylesheet> 
+0

谢谢,看我的编辑。 – user318747 2010-08-26 16:18:21

1

该样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text"/> 
    <xsl:template match="group/*[not(self::message)]"> 
     <xsl:value-of select="concat(.,substring(',&#xA;', 
               1 + boolean(self::field), 
               1))"/> 
    </xsl:template> 
    <xsl:template match="text()"/> 
</xsl:stylesheet> 

输出:

345,265,true 
333,false 
+0

@Alejandro:不错的紧凑代码。 +1 – 2010-08-26 19:54:49