3

简单的库很棒,自从过去 3 天以来,我已经从肥皂服务器解析了许多不同的 XML,但是我遇到了带有“0”或“1”的布尔属性:

<list mybool1="0" mybool2="1" attr1="attr" attr2="attr">
    <page mybool3="1">
        ...
    </page>
    <page mybool3="0">
        ...
    </page>
    ...
</list>

我试图创建这个类:

public class Boolean01Converter implements Converter<Boolean>
{
    @Override
    public Boolean read(InputNode node) throws Exception {
        return new Boolean(node.getValue().equals("1"));
    }
    @Override
    public void write(OutputNode node, Boolean value) throws Exception {
        node.setValue(value.booleanValue()?"1":"0");
    }
}

并在我的对象定义上实现它:

@Root(name="list")
public class ListFcts
{
    @Attribute
    @Convert(Boolean01Converter.class)
    private Boolean mybool1;

    @Attribute
    @Convert(Boolean01Converter.class)
    private Boolean mybool2;

    @Attribute
    private int ...

    @ElementList(name="page", inline=true)
    private List<Page> pages;

    public Boolean getMybool1() {
        return mybool1;
    }
}

但是对于每个布尔值,我仍然是错误的。

[edit] 事实上,当我这样做时:

@Override
public Boolean read(InputNode node) throws Exception {
    return true;
}

我仍然得到false

Serializer serial = new Persister();
ListFcts listFct = serial.read(ListFcts.class, soapResult);
if(listFct.getMybool1())
{
    //this never happens
}else{
    //this is always the case
}

所以我的转换器没有影响......

另外:如何将转换器附加到 Persister 而不是在@Attributes 上声明它一百次?

提前谢谢了 !!

[edit2]

我放弃了转换器,这是我自己的解决方案:

@Root(name="list")
public class ListFcts
{
    @Attribute
    private int mybool1;

    @Attribute
    private int mybool2;

    public int getMybool1() {
        return mybool1;
    }

    public Boolean isMybool1() {
        return (mybool1==1)?true:false;
    }

    ...
}
4

2 回答 2

2

您的代码正在使用node.getValue()它返回每个 XML 节点的(读取:内容)(示例中的“...”位)。

您需要的是读取属性值,例如node.getAttributeValue("mybool1").equals("1")

于 2011-09-30T12:35:47.490 回答
0

我放弃了 Converter,我听说过 Transform 但没有找到如何使用它,所以这是我自己的基本解决方案:

@Root(name="list")
public class ListFcts
{
    @Attribute
    private int mybool1;

    @Attribute
    private int mybool2;

    public int getMybool1() {
        return mybool1;
    }

    public Boolean isMybool1() {
        return (mybool1==1)?true:false;
    }

    ...
}
于 2011-10-10T08:57:32.457 回答