2012-09-20 37 views
0

我有以下XML:XSLT轉換誤差

<RootNode xmlns="http://someurl/path/path/path"> 
    <Child1> 
     <GrandChild1>Value</GrandChild1> 
     <!-- Lots more elements in here--> 
    </Child1> 
</RootNode> 

我有以下XSLT:

<xsl:stylesheet version="1.0" xmlns="http://someurl/path/path/path" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/> 
    <xsl:template match="/"> 
     <NewRootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
      <NewChild1> 
       <xsl:for-each select="RootNode/Child1"> 
        <NewNodeNameHere> 
         <xsl:value-of select="GrandChild1"/> 
        </NewNodeNameHere> 
       <!-- lots of value-of tags in here --> 
       </xsl:for-each> 
      </NewChild1> 
     </NewRootNode > 
    </xsl:template> 
</xsl:stylesheet> 

問題:這是我的結果:

<?xml version="1.0" encoding="utf-8"?> 
<NewRootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <NewChild1 /> 
</NewRootNode> 

我期待看到:

<?xml version="1.0" encoding="utf-8"?> 
<NewRootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <NewChild1> 
     <NewNodeNameHere>Value</NewNodeNameHere> 
     <!-- Other new elements with values from the xml file --> 
    </NewChild1> 
</NewRootNode> 

我缺少NewChild1裏面應該有的信息。

我認爲我的for-each選擇是正確的,所以我唯一能想到的就是Xml中的名稱空間和xslt中的名稱空間存在問題。任何人都可以看到我在做什麼錯了嗎?

回答

1

樣式表命名空間應該是http://www.w3.org/1999/XSL/Transform而不是http://someurl/path/path/path

此外,由於輸入XML使用命名空間所有的XPath表達式應該是合格的命名空間:

<xsl:template match="/" xmlns:ns1="http://someurl/path/path/path"> 
    <NewRootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
     <NewChild1> 
     <xsl:for-each select="ns1:RootNode/ns1:Child1"> 
      <NewNodeNameHere> 
       <xsl:value-of select="ns1:GrandChild1"/> 
      </NewNodeNameHere> 
      <!-- lots of value-of tags in here --> 
     </xsl:for-each> 
     </NewChild1> 
    </NewRootNode> 
</xsl:template> 
2

問題是由命名空間所致。

由於xml定義了xmlns="http://someurl/path/path/path",它不再處於默認名稱空間中。

您可以在xsl中用名稱如xmlns:ns="http://someurl/path/path/path"來定義該名稱空間,然後在XPath表達式中使用該名稱。

對我來說,以下工作:

<xsl:stylesheet version="1.0" xmlns:ns="http://someurl/path/path/path" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/> 
    <xsl:template match="/"> 
    <NewRootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
     <NewChild1> 
      <xsl:for-each select="ns:RootNode/ns:Child1"> 
       <NewNodeNameHere> 
        <xsl:value-of select="ns:GrandChild1"/> 
       </NewNodeNameHere> 
      <!-- lots of value-of tags in here --> 
      </xsl:for-each> 
     </NewChild1> 
    </NewRootNode > 
    </xsl:template> 
</xsl:stylesheet>