使用xslt选择第一个xml节点

时间:2011-06-08 11:00:44

标签: xml xslt

我有以下xml,

<?xml version="1.0" encoding="utf-8"?>
<NewDataSet xmlns="www.asdsad.com/sdsad">
  <Balances>
    <AccountNumber>KK-888</AccountNumber>
    <SubAccountNumber>KK-888-1</SubAccountNumber>
    <TAcctID>1</TAcctID>
    <TransactionAccount>ARC Deposit</TransactionAccount>
    <Description />
    <Balance>0.0000</Balance>
  </Balances>
  <Balances>
    <AccountNumber>KK-888</AccountNumber>
    <SubAccountNumber>KK-888-2</SubAccountNumber>
    <TAcctID>2</TAcctID>
    <TransactionAccount>Assessments and Dues</TransactionAccount>
    <Description>This is the primary account for all associations dues and assessments. </Description>
    <Balance>170</Balance>
  </Balances>
  <Balances>
    <AccountNumber>KK-888</AccountNumber>
    <SubAccountNumber>KK-888-4</SubAccountNumber>
    <TAcctID>4</TAcctID>
    <TransactionAccount>Fines/Compliance</TransactionAccount>
    <Description />
    <Balance>0.0000</Balance>
  </Balances>
</NewDataSet>

我需要通过xslt,

从上面得到这个结果xml
<balance amount="170" />

我会将SubAccountNumber传递给xslt,我需要特定的余额/余额金额。在上面的例子中,我将SubAccountNumber值传递为“KC1-0221-2”,因此第二个Balances节点匹配,它的Balance值为“170”。任何人都可以帮我写xslt。 (注意:只有一个节点与传递的SubAccountNumber匹配)。

更新如果我能用根节点生成xml,我没问题,

<account>
     <balance amount="170" />
</account>

1 个答案:

答案 0 :(得分:1)

一个起点......

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:asd="www.asdsad.com/sdsad"
    exclude-result-prefixes="asd">

    <xsl:output omit-xml-declaration="yes"/>
    <xsl:param name="SAN" select="'KC1-0221-2'"/>

    <xsl:template match="/asd:NewDataSet">
        <balance amount="{asd:Balances[asd:SubAccountNumber=$SAN]/asd:Balance}"/>
    </xsl:template>

</xsl:stylesheet>

请注意,这将产生

<balance amount="" />

如果输入文档中不存在$SAN。否则,如果根本不匹配,你想如何回来?