0

当我在 java 中使用 XSLT 从 XML 转换为 JSON 时,会发生以下错误:

fn:xml-to-json() 的第一个参数的必需项类型是 node();提供的值具有项目类型 xs:string

XML:

<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="student">john</string>
   <string key="class">Bachelors</string>
   <string key="subjects">
         <subject>
            <subjects>maths</subjects>   
         </subject>
   </string>
</map>

XSLT(Xml 到 Json):

<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/> 
  <xsl:strip-space elements="*"/>
  <xsl:param name="xmlText"/>
  <xsl:template match="@*|node()"> 
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template> 
  <xsl:template name="init">
    <xsl:apply-templates select="xml-to-json($xmlText)"/> 
  </xsl:template>
</xsl:stylesheet>

错误 :

Type error at char 12 in xsl:copy-of/@select on line 30 column 50 of json2xml.xsl:
    XPTY0004: Required item type of first argument of fn:xml-to-json() is node(); 
    supplied value has item type xs:string Exception in thread "main" net.sf.saxon.s9api.SaxonApiException: 
    Required item type of first argument of fn:xml-to-json() is node(); 
    supplied value has item type xs:string at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:599) 
    at com.xmltojson.sampleclass.SimpleJaxp.main(SimpleJaxp.java:44)Caused by: net.sf.saxon.trans.XPathException: 
    Required item type of first argument of fn:xml-to-json() is node(); 
    supplied value has item type xs:string
4

1 回答 1

0

我对这个问题投了反对票,因为您显然没有对此给予足够的关注:错误消息指的xsl:copy-of是您向我们展示的代码中没有的指令;而且您还没有向我们展示如何调用样式表以及如何$xmlText提供 的值。

但是(合并评论中已经提出的建议),您需要:

(a) 确保 xml-to-json() 的参数是一个节点。如果您从 URI 开始,请调用 doc() 或 document() 函数来获取节点。如果您从包含词法 XML 的字符串开始,请调用 parse-xml() 函数。

(b) 确保您传递的节点对规范中定义的模式(对于 JSON 的 XML 表示)有效。例如,此架构不允许subject作为string. (我不确定您想在这里实现什么输出:如果您希望 JSON 输出采用以下形式

"subjects": "<subject><subjects>maths</subjects></subject>"

那么您应该将输入更改为

<string key="subjects"><![CDATA[<subject><subjects>maths</subjects></subject>]]></string>

(如果存在换行符,则会出现进一步的复杂情况,但这将是一个单独的问题)。

于 2017-07-27T09:52:16.947 回答