2013-02-23 70 views
1

开头的所有节点我正在尝试执行XSLT转换,其中输入XML是任意的。唯一不变的是它会有一个名字以'first'开头的节点。我需要获得该节点的价值,它是直接的兄弟姐妹。但是,以下模板仅生成XML声明。XSLT:选择以

重要的是,这段代码在Ruby中使用Nokogiri XML解析器。不过,我认为这更像是一个XSLT/XPath问题,而不是一个Ruby问题,因此标记相应。

输入XML:

<?xml version="1.0"?> 
<employees> 
    <employee> 
    <first_name>Winnie</first_name> 
    <last_name>the Pooh</last_name> 
    </employee> 
    <employee> 
    <first_name>Jamie</first_name> 
    <last_name>the Weeh</last_name> 
    </employee> 
</employees> 

所需的输出XML:

<?xml version="1.0"?> 
<people> 
    <person> 
    <first>Winnie</first> 
    <last>the Pooh</last> 
    </person> 
    <person> 
    <first>Jamie</first> 
    <last>the Weeh</last> 
    </person> 
</people> 

XSLT:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="xml" indent="yes" encoding="UTF-8" /> 
<xsl:template match="/"> 
    <xsl:for-each select="node()[starts-with(name(), 'first')]"> 
    <people> 
     <person> 
     <name> 
     <first><xsl:value-of select="." /></first> 
     <last><xsl:value-of select="following-sibling::*[1]" /></last> 
    </name> 
     </person> 
    </people> 
    </xsl:for-each> 
</xsl:template> 
    </xsl:stylesheet> 
+0

我想通了自己正确的作用,但对于那些谁该页面寻找一个解决方案的落地,请参阅我的回答如下。 – 2013-02-23 20:47:55

回答

1
<?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" indent="yes" encoding="UTF-8" /> 
    <!-- match the node that has a name starting with 'first' --> 
    <xsl:template match="node()[starts-with(name(), 'first')]"> 
    <xsl:element name="people"> 
     <xsl:element name="person"> 
     <xsl:element name="name"> 
      <xsl:element name="first"> 
      <xsl:value-of select="." /> 
      </xsl:element> 
      <xsl:element name="last"> 
      <xsl:value-of select="following-sibling::*[1]" /> 
      </xsl:element> 
     </xsl:element> 
     </xsl:element> 
    </xsl:element> 
    <xsl:apply-templates /> 
    </xsl:template> 
    <!-- stop the processor walking the rest of the tree and hitting text nodes --> 
    <xsl:template match="text()|@*" /> 
</xsl:stylesheet> 
3

如果输入XML与您的建议一样随心所欲,我不知道如何将员工/员工更改为个人/人员。但是,您可以实现大致与

<xsl:template match="*"> 
    <xsl:copy><xsl:apply-templates/></xsl:copy> 
</xsl:template> 

<xsl:template match="*[starts-with(name(), 'first')]"> 
    <first><xsl:apply-templates/></first> 
</xsl:template> 

<xsl:template match="*[preceding-sibling::*[1][starts-with(name(), 'first')]]"> 
    <last><xsl:apply-templates/></last> 
</xsl:template> 
+0

我自己想清楚了,请看我的答案。尽管多谢你的回应。 – 2013-02-23 20:34:39