2016-08-26 34 views
0

由於xmlns,下面的xml不能轉換,我嘗試了沒有xmlns,它按預期工作。但我正在接受xmlns的輸入。請建議我如何克服它。由於xmlns,無法轉換xml

要求:從xml中檢索productBenefitHeaders。

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<productData xmlns="http://www.example.org/consolidated"> 
<productResponse> 
    <product> 
     <status> 
      <isError>false</isError> 
     </status> 
     <productBenefit> 
      <productBenefitCategory>CARDs</productBenefitCategory> 
      <productBenefitId>12AA</productBenefitId> 
      <productBenefitHeader>Philips</productBenefitHeader> 
     </productBenefit> 
     <productBenefit> 
      <productBenefitCategory>CARDs</productBenefitCategory> 
      <productBenefitId>12AB</productBenefitId> 
      <productBenefitHeader>Samsung</productBenefitHeader> 
     </productBenefit> 
    </product> 
</productResponse> 
<productData> 

XSLT:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="html" indent="yes" encoding="UTF-8" omit-xml-declaration="no"/> 
<xsl:template match="/"> 
<xsl:for-each select="productData/productResponse/product/productBenefit">   
<xsl:value-of select="productBenefitHeader"/> 
    </xsl:for-each> 
</xsl:template> 
</xsl:stylesheet> 
+0

嘗試在網站上搜索'default namespaces'。 –

+1

請參閱(例如):http://stackoverflow.com/questions/34758492/xslt-transform-doesnt-work-until-i-remove-root-node/34762628#34762628 –

回答

1

在源XML的元素是命名空間中的http://www.example.org/consolidated。而您正在搜索元素而不指定名稱空間。

要使用名稱空間進行搜索,您需要在stylesheet標記中添加命名空間併爲其設置前綴,在這種情況下,我使用了'pref'。

xmlns:pref="http://www.example.org/consolidated" 

現在,您可以在指定要查找的元素的同時在xsl中使用前綴。這是你的xsl,但添加了前綴。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:pref="http://www.example.org/consolidated"> 
<xsl:output method="html" indent="yes" encoding="UTF-8" omit-xml-declaration="no"/> 
    <xsl:template match="/"> 
    <xsl:for-each select="pref:productData/pref:productResponse/pref:product/pref:productBenefit">   
    <xsl:value-of select="pref:productBenefitHeader"/> 
    </xsl:for-each> 
</xsl:template> 
</xsl:stylesheet> 

此外,請確保您的結束標記是正確的。目前,您示例xml中的最後一個標記不是結束標記。