Xstream问题和java对象

时间:2010-08-22 22:46:16

标签: java xstream

我正在寻找构建java对象

<placement_rules>
  <section name="news">
    <front_order>
       <article_type name="article1"></article_type>
       <article_type name="article2"></article_type>
    </front_order>
    <back_order>
       <article_type name="article3"></article_type>
    </back_order>
  </section>
  <section name="sports">
    <front_order>
      <article_type name="article4"></article_type>
    </front_order>
    <back_order>
      <article_type name="article5"></article_type>
      <article_type name="article6"></article_type>
    </back_order>
  </section>
</placement_rules>

我需要创建哪些对象?

我从SectionRule.java里面开始

@XStreamAsAttribute
@XStreamAlias("name")
private String sectionName;

@XStreamAlias("front_order")
private List<ConfigPlacementNode> frontOrder = new ArrayList<ConfigPlacementNode>(0);

@XStreamAlias("back_order")
private List<ConfigPlacementNode> backOrder = new ArrayList<ConfigPlacementNode>(0);

如何在其周围创建其他第一类对象?任何帮助将受到高度赞赏。

此致 阿玛尔

1 个答案:

答案 0 :(得分:1)

我从未使用过XStream,但可以使用以下对象模型来表示XML文档。我已经包含了标准的JAXB注释(包含在Java SE 6中)来演示XML mappping。

<强> PlacementRules

import java.util.List;
import javax.xml.bind.*;

@XmlRootElement(name="placement_rules")
@XmlAccessorType(XmlAccessType.FIELD)
public class PlacementRules {

    private List<Section> section;

}

栏目

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Section {

    @XmlAttribute
    private String name;

    @XmlElementWrapper(name="front_order")
    @XmlElement(name="article_type")
    private List<Article> frontOrderArticles;

    @XmlElementWrapper(name="back_order")
    @XmlElement(name="article_type")
    private List<Article> backOrderArticles;

}

<强>文章

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Article {

    @XmlAttribute
    private String name;

}

下面是一个示例程序,用于演示它的工作原理:

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(PlacementRules.class);

        Unmarshaller unmarshaller = context.createUnmarshaller();
        File xml = new File("src/forum38/input.xml");
        PlacementRules placementRules = (PlacementRules) unmarshaller.unmarshal(xml);

        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(placementRules, System.out);
    }
}