这是我问题的后续:标记模板驱动的提取和三倍:处理数组节点
所以假设我有许多像这样构成的文档:
declareUpdate();
xdmp.documentInsert(
'/test/tde.json',
{
content: {
name:'Joe Parent',
children: [
{
name: 'Bob Child'
},
{
name: 'Sue Child'
},
{
name: 'Guy Child'
}
]
}
},
{permissions : xdmp.defaultPermissions(),
collections : ['test']})
我想定义一个模板,该模板可以从这些文档中提取三倍,以定义孩子之间的兄弟姐妹关系。在上面的示例中,我想提取以下三元组(关系是双向的):
Bob Child sibling-of Sue Child
Bob Child sibling-of Guy Child
Sue Child sibling-of Bob Child
Sue Child sibling-of Guy Child
Guy Child sibling-of Bob Child
Guy Child sibling-of Sue Child
如何设置模板来完成此操作?
谢谢!
我不知道这样做的方法,但似乎任何"兄弟姐妹"的关系都等同于两个"孩子的关系"。你能做这样的事情吗?
{
?x is-parent-of ?a-child .
?x is-parent-of ?b-child.
?a-child != ?b-child
}
,或者,如果您可以使用推理规则,则可以构建一个定义这样的"兄弟姐妹"的规则。然后,尽管该模板没有直接生成"兄弟姐妹",但由于模板生成" Is-Parent of"三元组。<<<<<<<<
我将JSON转换为XML,写了XSLT转换以获取XML三元组。后来的XML可以在需要时转换回JSON。
XSLT转换:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:json="http://marklogic.com/xdmp/json/basic" xmlns:sem="http://marklogic.com/semantics" exclude-result-prefixes="json">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="json:content">
<sem:triples xmlns:sem="http://marklogic.com/semantics">
<xsl:apply-templates select="json:children"/>
</sem:triples>
</xsl:template>
<xsl:template match="json:children">
<xsl:for-each select="json:json">
<xsl:variable name="subjectName">
<xsl:value-of select="json:name/text()"/>
</xsl:variable>
<xsl:for-each select="following-sibling::* | preceding-sibling::* ">
<sem:triple>
<sem:subject>
<xsl:value-of select="$subjectName"/>
</sem:subject>
<sem:predicate>sibling-of</sem:predicate>
<sem:object><xsl:value-of select="json:name/text()"/></sem:object>
</sem:triple>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Xquery代码将JSON转换为XML并进行转换:
xquery version "1.0-ml";
import module namespace json = "http://marklogic.com/xdmp/json" at "/MarkLogic/json/json.xqy";
declare namespace sem = "http://marklogic.com/semantics";
declare variable $j := '{"content": {"name": "Joe Parent","children": [{"name": "Bob Child"}, {"name": "Sue Child"}, {"name": "Guy Child"}]}}';
let $doc := json:transform-from-json($j),
$xslt := doc("myTemplates.xsl"),
$result := xdmp:xslt-eval($xslt,$doc),
$config := json:config("custom"),
$_ := map:put($config, "whitespace", "ignore"),
$_ := map:put($config, "array-element-names", ("triple")),
$_ := map:put($config, "element-namespace","http://marklogic.com/semantics")
return json:transform-to-json($result, $config)