将xml转换为json时出错

时间:2017-07-26 14:38:30

标签: xslt xml-parsing xslt-2.0 saxon xslt-3.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

1 个答案:

答案 0 :(得分: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>

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

相关问题