如何根据父元素属性值映射值

时间:2016-04-26 12:07:44

标签: dataweave

输入,在attbribute下可以有n个实体和多个值: 这是基本的例子:

<?xml version="1.0" encoding="UTF-8"?>
<entityset>
    <entity name="dog">
        <attribute code="app">
            <value>my application</value>
        </attribute>
        <attribute code="1code">
            <value>dog1value</value>
        </attribute>
        <attribute code="">
            <value>dog2value</value>
        </attribute>
    </entity>
    <entity name="cat">
        <attribute code="app">
            <value>my cat application</value>
        </attribute>
        <attribute code="1code">
            <value>cat1value</value>
        </attribute>
        <attribute code="2code">
            <value>cat2value</value>
        </attribute>
    </entity>
</entityset>

我的DW为初学者:

{
    insert: payload.entityset.*entity map {
        id: $.@name,
        name: $.attribute.value when $.attribute.@code=='1code' otherwise '',
        owner: $.attribute.value when payload.entityset.entity.attribute.@code=='2code' otherwise ''    

    }

}

期望的输出:

<insert>
   <record>
       <id>dog</id>
       <name>dog1value</name>
       <owner>dogvalue2</owner>
    </record>
    <record>
        <id>cat</id>
        <name>cat1value</name>
        <owner>cat2value<owner>
    </record>
 </insert>

我无法弄清楚如何制造条件  如果属性。@ code ==&#34; 1code&#34;然后将attributa.value映射到。和code2属性到所有者。 我正在读取xml文件的输入。当我尝试介绍&#34; map&#34;然后我总是出错:

异常堆栈是: 1.无法将a:数组强制转换为:object(com.mulesoft.weave.model.values.coercion.exception.UnsupportedTypeCoercionException)   com.mulesoft.weave.model.values.coercion.ObjectTypeCoercionValue:31(null) 2.执行时的例外情况:     insert:payload.entityset。* entity map {                               ^ 无法强制a:数组到:object(com.mulesoft.weave.mule.exception.WeaveExecutionException)   com.mulesoft.weave.mule.WeaveMessageProcessor $ WeaveOutputHandler:166(null)

1 个答案:

答案 0 :(得分:0)

*选择器的结果是一个数组,因此您不能将其映射为对象。同样,在对象的级别下降时,很容易忽略当前级别。该脚本达到了预期的结果:

%dw 1.0
%output application/xml
---
{
    insert: payload.entityset.*entity mapObject {
        record: {
            id: $.@name,
            name: (($.*attribute  filter ($.@code=='1code')) map ($.value))[0] default '',
            owner: (($.*attribute  filter ($.@code=='2code')) map ($.value))[0] default ''
        }
}