簡體   English   中英

刪除空屬性xquery3.0

[英]remove empty attributes xquery3.0

這是我的xml示例。

 let $test :=   
    <root>
        <a z="">stuff</a>
        <b z="12" y="">more stuff</b>
        <c>stuff</c>
        <d z = " " y="0" x ="lkj">stuff goes wild</d>
    </root>

我想使用查詢刪除空屬性以獲取此信息:

<root>
    <a>stuff</a>
    <b z="12">more stuff</b>
    <c>stuff</c>
    <d y="0" x ="lkj">stuff goes wild</d>
</root>  

我的查詢已經到了這一步,但是我不能只刪除空屬性,而不能刪除所有屬性(如果元素中有空屬性)。

declare function local:sanitize ($nodes as node()*) {
for $n in $nodes 
return typeswitch($n)
    case element() return 
        if ($n/@*[normalize-space()='']) then  (element{node-name($n)} {($n/@*[.!=''], local:sanitize($n/node()))})
        else (element {node-name($n)} {($n/@*, local:sanitize($n/node()))})
default return ($n)
};

該功能需要高性能,因此我希望使用typeswitch。 我感覺很近,但最后一步似乎使我難以理解。 即。 z =“”不會被捕獲。 謝謝您的幫助。

代碼的問題在於,當重新創建元素時,您要檢查的是完全空的屬性,而不是空白歸一化后的空屬性。 加上這個,就可以了。

if ($n/@*[normalize-space()='']) then  (element{node-name($n)} {($n/@*[normalize-space(.)!=''], local:sanitize($n/node()))})

我簡化了模式,並區分了屬性,元素和其他所有內容。 篩選空屬性,重新創建元素,然后返回其他任何內容。 結果函數更易於閱讀和理解,並產生正確的輸出:

declare function local:sanitize ($nodes as node()*) {
for $node in $nodes 
return typeswitch($node)
  (: filter empty attributes :)
  case attribute() return $node[normalize-space(.)]
  (: recreate elements :)
  case element() return 
    element { node-name($node) } {
      (: Sanitize all children :)
      for $child in $node/(attribute(), node())
      return local:sanitize($child)
    }
  (: neither element nor attribute :)
  default return $node
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM