2012-09-20 34 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>