如何使用XStream将对象的数据部分转换为XML?

时间:2017-03-02 12:31:24

标签: java xml xstream

首先,如果问题不明确,我很抱歉。我正在尝试使用XStream在对象中创建XML及其内容。

以下是我试图实现的XML形式:

<Tag attr1 = "some_value" attr2 = "some_value"> CONTENT </Tag>

我在设计课程时遇到了麻烦。

以下是我到目前为止实施的方法:

@XStreamAlias("Tag")
public class Tag {

  @XStreamAsAttribute
  private String attr1;

  @XStreamAsAttribute
  private String attr2;

  private String content;

  public Tag(String content) {

    this.content = content;
  }

  // Getters for all three

  // Setters for all three
}

现在,当我执行以下操作时:

Tag tag = new Tag("Content");
tag.setAttr1("some_value");
tag.setAttr2("some_value");
XStream xStream = new XStream();
xStream.processAnnoations(Tag.class);
System.out.println(xStream.toXML(tag));

我使用额外的<content>标记获取XML。我不想要额外的<content>标记,我希望它是<Tag>的内容。我如何使用XStream做到这一点?

1 个答案:

答案 0 :(得分:0)

只需添加@XStreamConverter(value=ToAttributedValueConverter.class, strings={"content"})转换器。

@XStreamConverter(value=ToAttributedValueConverter.class, strings={"content"})
@XStreamAlias("Tag")
public class Tag {

  @XStreamAsAttribute
  String attr1;

  @XStreamAsAttribute
  String attr2;

  String content;

  public Tag(String content) {
    this.content = content;
  }


  public static void main(String[] args) {
      Tag tag = new Tag("Content");
      tag.attr1 = "some_value";
      tag.attr2 = "some_value";
      XStream xStream = new XStream();
      xStream.processAnnotations(Tag.class);
      System.out.println(xStream.toXML(tag));
  }
}