【问题标题】:Convert child nodes into a single string using XQuery in ML 10在 ML 10 中使用 XQuery 将子节点转换为单个字符串
【发布时间】:2023-01-19 22:43:53
【问题描述】:

我们有一个后端 ML 响应格式为 JSON 的应用程序,我们有一个包含文本和节点的元素,如下所示。 <Title>Header <bold>abc</bold></Title>

现在,在将上述节点转换为 JSON 时,我们得到的输出为 "Title": {"bold": "abc","_value": "Header "}

但是要在 UI 中应用格式,我们需要完整的(文本+节点)数据作为_value "Title": {"_value": "Header <bold>abc</bold>"}

我尝试使用 xdmp:quote() 将节点转换为字符串,但我需要保留 <Title> 作为节点。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: xml xquery marklogic marklogic-10


    【解决方案1】:

    您可以规范化 XML 内容,使用 xdmp:quote()“展平”内联元素并将它们转换为作为 title 值的一部分的转义字符串,以便 JSON 转换过程只是转换 title 元素 @987654324 @ 转换为 JSON 属性字符串。

    一个简单的 XSLT,可通过您的示例 XML 实现该目的:

    import module namespace json = "http://marklogic.com/xdmp/json"
        at "/MarkLogic/json/json.xqy";
    
    let $doc := <Title>Header <bold>abc</bold></Title>
    
    let $xslt := 
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0" 
      xmlns:xdmp="http://marklogic.com/xdmp" extension-element-prefixes="xdmp">
      
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>
      
      <!--quote any inline elements to make them escaped strings that are part of the parent element value, rather than child elements-->
      <xsl:template match="bold|italics|underline">
        <xsl:sequence select="xdmp:quote(.)"/>
      </xsl:template>
      
    </xsl:stylesheet>
    let $normalized-doc := xdmp:xslt-eval($xslt, $doc)
    
    let $custom :=
      let $config := json:config("custom") => map:with("whitespace", "ignore" )
      return $config
    return json:transform-to-json($normalized-doc, $custom)
    

    并产生以下输出:

    {
    "Title": "Header <bold>abc</bold>"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 2013-01-14
      • 1970-01-01
      相关资源
      最近更新 更多