开发者

Self closing tags with XStream?

Is there a way to get XStream to generate self closing elements?

E.g.

开发者_运维问答
<foo/>

instead of

<foo></foo>


There doesn't seem to be an explicit way to do this, since it's not supposed to matter to downstream XML processors.

You might take a look at the source for the PrettyPrintWriter class, which is probably what it's using.


I solved the problem using a little Workaround. In particular XStream prints selfclosing tags only for non-primitive object; so I replaced all String objects with a Generic class called "Element" with only one attribute, "value".

public class Element {
    private String value;
    public Element() {
    }
    public Element(String value) {
        this.value = value;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
}

In this way null values of Element will be printed in XML as selfclosing tags (as I wish)

After I wrote a custom converter to avoid printing in XML the tag for not empty objects.

public class CustomElementConverter implements Converter
{
    public boolean canConvert(Class type)
    {
        return type.equals(Element.class);
    }
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        String element = ((Element)source).getValue();
        if (element != null) { 
            writer.setValue(element);
        }
    }
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        return null;
    }
}

And it worked! I hope it will be useful to someone else.

Dom


you can use a converter and then set value with: writer.setValue("");

like this:

public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    Ack ack = (Ack)source;

    writeBasicAck(writer, ack);

    writer.setValue("");
}

protected void writeBasicAck(HierarchicalStreamWriter writer, Ack ack) {
    writer.addAttribute("pos", String.valueOf(ack.getPos()));
    writer.addAttribute("ticket", String.valueOf(ack.getTicket()));
    writer.addAttribute("estado", String.valueOf(ack.getEstado()));
    writer.addAttribute("suc", String.valueOf(ack.getSucursal()));
}

this write:

<ackticket pos="2" ticket="123" estado="0" suc="1235"></ackticket>

instead of:

<ackticket pos="2" ticket="123" estado="0" suc="1235"/>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜