如何解决dataweave 2.0转换
我有一个XML文件,其中包含嵌套元素,并且很少有元素具有该属性。我想使用dataweave 2.0将此XML转换为json,并且json必须包含属性。
Using the json generated from previous step,I want to recreate the original XML
Ex: <elem1>
<elem2 attr=Val>
<elem3 attr=Val>
</elem3>
</elem2>
</elem1>
Thanks in advance
解决方法
具有属性的JSON到具有属性的XML:
%dw 2.0
output application/xml
fun collectAttributes(elem:Object) =
elem filterObject ((value,key,index) -> key contains "@" )
fun putAttributes(elem: Object) =
elem mapObject ((value,index) -> value match {
case is Object -> do {
var attr = collectAttributes(value)
var withoutAttr = value -- attr
---
(key) @((attr)):
if (keysOf(withoutAttr) contains "__text" as Key)
withoutAttr."__text"
else
putAttributes(withoutAttr)
}
else -> (key): value
})
---
putAttributes(payload)
我不确定是否可以将每个带有JSON的JSON完全推广,但是可以根据您的情况使用。
具有属性的XML到JSON:
您可以尝试使用writer属性writeAttributes
。
%dw 2.0
output application/json writeAttributes=true
---
payload
https://docs.mulesoft.com/mule-runtime/4.3/dataweave-formats-json#properties
,您可以尝试使用此脚本将其转换回xml
%dw 2.0
output application/xml writeDeclaration=false
fun json2xml(data) = data mapObject (v,k,i) -> {
((k) @(
(
if(v is Object and !isEmpty(searchForAttr(v))) searchForAttr(v)
else null
)
): v match {
case is Object -> if(namesOf(v) contains("__text")) searchForText(v) else json2xml(v)
else -> v
}) if (!(k contains "@") and !(k contains "__text"))
}
fun searchForAttr(v) = v mapObject {
(($$[1 to -1]): $) if(($$ as String) startsWith("@"))
}
fun searchForText(v) = v mapObject {
(($$):$) if(($$ as String) == "__text")
} pluck $
---
json2xml(payload)
我用更复杂的xml结构进行了尝试,并且确实转换回了原始xml,但是最初转换为JSON(使用writeAttributes
选项)则没有xml命名空间,因此如果原始输入中包含命名空间可能需要通过JSON转换走另一条路。
使用Christian的方法,您可以更新脚本以从属性键中删除“ @”:
%dw 2.0
output application/xml
fun collectAttributes(elem:Object) =
elem filterObject ((value,index) -> value match {
case is Object -> do {
var attr = (collectAttributes(value))
var attrfinal = attr mapObject {
($$ replace "@" with ""):(($))
}
var withoutAttr = value -- attr
---
(key) @((attrfinal)):
if (keysOf(withoutAttr) contains "__text" as Key)
withoutAttr."__text"
else
putAttributes(withoutAttr)
}
else -> (key): value
})
---
putAttributes(payload)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。