如何将空字符串序列化为单个空标记? [英] How to serialize a null string as a single empty tag?

查看:155
本文介绍了如何将空字符串序列化为单个空标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Simple XML框架序列化这个类:

I serialize this class using the Simple XML framework:

@Root
public class HowToRenderEmptyTag {
    @Element(required=false)
    private String nullString;
}

我想得到:

<howToRenderNull>
    <nullString/>
</howToRenderNull>

但我得到:

<howToRenderNull/>

我试过分配一个空字符串:

I have tried assigning an empty string:

@Root
public class HowToRenderEmptyTag {
    @Element(required=false)
    private String emptyString = "";
}

但是我得到一个开头和一个结束标签:

But then I get one opening and one closing tag:

<howToRenderNull>
    <emptyString></emptyString>
</howToRenderNull>

使用XML并且更改客户端超出范围的客户端不能正确接受这一点。

This is not sadly accepted correctly by the client consuming the XML and changing the client is out of scope.

关于如何获得单个空标记的任何想法?

Any ideas on how to get the single empty tag?

推荐答案

你可以在这里使用一个技巧;为你的元素写一个转换器来改变行为:

You can use a trick here; write a converter for your element which changes the behaviour:

@Root(name = "howToRenderEmptyTag")
public class HowToRenderEmptyTag
{
    @Element(name = "emptyString", required = false)
    @Convert(value = EmptyElementConverter.class) // Set the converter for this element
    private String nullString;


    // ...
}



EmptyElementConverter class:



EmptyElementConverter class:

public class EmptyElementConverter implements Converter<String>
{
    @Override
    public String read(InputNode node) throws Exception
    {
        /* Implement if required */
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void write(OutputNode node, String value) throws Exception
    {
        /* Simple implementation: do nothing here ;-) */
    }
}

你不必实现这个字符串的转换器 - 在本例中,它是可选的。您可以保持该类通用或为 Object 实现它,这样您就可以将它用于任何元素之王。

You don't have to implement this Converter for strings - in this example it's optional. You can keep the class generic or implement it for Object so you can use it for any king of element.

final File f = new File("test.xml");

HowToRenderEmptyTag example = new HowToRenderEmptyTag("");

Serializer ser = new Persister(new AnnotationStrategy()); // Don't forget AnnotationStrategy here!
ser.write(example, f);

最后结果:

<howToRenderEmptyTag>
   <emptyString/>
</howToRenderEmptyTag>

既然您已使用过两者,我不确定空元素是否需要名称 emptyString nullString 但改变它并不是一件大事: - )

Since you have used both, I'm not sure if the empty element needs the name emptyString or nullString but it's not a big thing to change it :-)

这篇关于如何将空字符串序列化为单个空标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆