使用XPath表达式进行XML到JSON的转换



我必须使用XPath表达式将XML转换为JSON格式。有什么办法可以让我做到这一点吗?

我尝试使用xml-to-json函数,但我不知道该如何为该函数提供参数。

我只需要运行XPath表达式,我不能使用XSLT来实现同样的目的。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
<location>DL</location>
</book>
<book category="children">
<title lang="es">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
<location>UP</location>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
<location>  DL</location>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
<location>dl </location>
</book>
<category>web</category>
</bookstore>

这确实扩展了XPath的功能,即使您有3.1版本。您应该真正使用XSLT或XQuery。

然而,我认为这是可能的,但不使用xml-to-json((函数。你需要像这样的东西

serialize (
map { "bookstore": 
array { //book !
map { "category" : string(@category),
"title" : string(title),
"authors" : 
array { author ! string(.) },
"year" : number(year)
}
}
},
map{"method" : "json"}
)

最新更新