2017-03-07 73 views
0

我有這樣的XML文件提取XML文件的一個子集,改變一個節點

<Person> 
    <Name> 
     <FirstName>John</FirstName> 
     <LastName>Doe</LastName> 
    </Name> 
    <Address> 
     <Street>Grand Street</Street> 
     <ZIP>1002</ZIP> 
     <City>New York</City> 
    </Address> 
</Person> 

我想有輸出:

<Address> 
    <Street>Changed Street</Street> 
    <ZIP>1002</ZIP> 
    <City>New York</City> 
</Address> 

所以其實我想提取 - 節點加改變單個節點

我試過下面的xsl,但它只提取了地址節點而沒有改變街道節點的值。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output omit-xml-declaration="yes" indent="yes" /> 
    <xsl:strip-space elements="*"/> 

    <xsl:template match="/Person/Address"> 
     <xsl:copy-of select="." /> 
    </xsl:template> 

    <xsl:template match="/Address/Street"> 
     <Street>Changed Street</Street> 
    </xsl:template> 

    <xsl:strip-space elements="*"/> 
    <xsl:template match="text()|@*"/> 

</xsl:stylesheet> 

有沒有人知道可能性?

回答

0

開始嘗試了與身份模板...

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

然後你只需要擔心有您要更改文檔的部分模板。

因此,只選擇Address元素,你可以做到這一點與此模板...

<xsl:template match="Person"> 
    <xsl:apply-templates select="Address" /> 
</xsl:template> 

注意使用xsl:apply-templates,而不是xsl:copy-of,因爲這將允許模板被應用到任何後代節點。

要更改地址的節點,有一個這樣的模板......

<xsl:template match="Address/Street"> 
    <Street>Changed Street</Street> 
</xsl:template> 

注意在國家缺乏/。表達式開始處的/表示文檔節點,因此/Address只會匹配地址(如果它是文檔的根元素)。

試試這個XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output method="xml" indent="yes" /> 

    <xsl:template match="Person"> 
     <xsl:apply-templates select="Address" /> 
    </xsl:template> 

    <xsl:template match="Address/Street"> 
     <Street>Changed Street</Street> 
    </xsl:template> 

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

注意,目前的XSLT似乎暗示要忽略的屬性(不是你的XML樣本具有屬性),但如果你是真的想忽略他們,改變過去模板來代替...

<xsl:template match="node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()"/> 
    </xsl:copy> 
</xsl:template>