【发布时间】:2019-02-11 21:23:30
【问题描述】:
我有一些 JSON、一个 XPath 和一个值。我想用新值替换 XPath 指向的 JSON 属性中的现有值。我在想我可以用 XSLT 做到这一点,但我不太擅长 XSLT。这将在 XQuery 模块中。
对于 XML,我可以这样做:
let $content :=
document {
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
</class>
}
let $template :=
<xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">
<xsl:template match = "node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="student/marks">
<foo>bar</foo>
</xsl:template>
</xsl:stylesheet>
return
xdmp:xslt-eval($template, $content)
这会正确地将 class/student/marks 元素替换为 <foo>bar</foo> 元素。
对于 JSON,我正在尝试这个:
let $stuff :=
document {
object-node {
"SomeProperty": object-node {
"LowProperty1":"some string",
"LowProperty2":"some string",
"LowProperty3": array-node { "some string 1", "some string 2"}
}
}
}
let $target := xdmp:unpath("/EvenLowerProperty/LowestProperty1", (), $stuff)
return
xdmp:xslt-eval(
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0"
xmlns:json="http://marklogic.com/xdmp/json">
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="SomeProperty/LowProperty1">
{
map:entry("LowProperty1", "bar")
}
</xsl:template>
</xsl:stylesheet>,
$stuff
)
我想这样结束:
{
"SomeProperty": {
"LowProperty1":"bar",
"LowProperty2":"some string",
"LowProperty3": [ "some string 1", "some string 2" ]
}
}
相反,我得到的是原件的副本。我尝试了一些变化,但我没有更接近。我应该期望这行得通吗?
【问题讨论】: