2017-07-26 94 views
-1

当我从XML在Java中使用XSLT转换为JSON出现以下错误:出错转换XML来JSON

必需项类型FN的第一个参数的:XML到JSON()是节点();提供的值具有项目类型的xs:串

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 
+0

那么,你如何传递参数?考虑简单地传递XML作为主要输入文档并使用例如''或者确保你传入的参数不是但只有一个节点。或者,如果你有一个字符串参数,那么你可以使用''。 –

+0

此外,您拥有的XML不是用于输入到'xml-to-json'的模式的有效实例,我认为,所以您需要首先将其转换为删除'subject'内容或转义它以确保'string key =“subjects”的内容是一个简单的字符串。 –

+0

@MartinHonnen当我传递字符串作为xml-to-json(parse-xml($ xmlText))时,它将抛出xml-to-json:在错误的命名空间中找到的元素:Q {} Event。 – bookofcodes

回答

0

我对这个问题投了反对票,因为你显然没有足够小心:错误信息指的是一个xsl:copy-of指令,它不在你向我们显示的代码中;而且您没有向我们展示样式表是如何调用的以及$xmlText的值是如何提供的。

但是(巩固已经取得的在评论中建议),您需要:

(一)确保参数XML到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> 

(其它并发症出现如果有换行符,但这将是一个单独的问题)。