在Java中的xmlElement上添加xmlAttribute

时间:2017-12-19 14:31:47

标签: java xml solr

我正在尝试为Solr创建一个xml文件,但是我遇到了一个问题。我使用@XmlElement注释告诉marhaller我的类的xml元素是这样的:

@XmlElement(name = "field")
public String getAuthors() {
    return authors;
}

public void setAuthors(List<String> authors) {
    setValue(authors, "authors");
}

@XmlElement(name = "field")
public String getDate() {
    return date;
}

public void setDate(List<String> date) {
    setValue(date, "date");
}

@XmlElement(name = "field", required = false)
public String getContent() {
    return content;
}

public void setContent(List<String> content) {
    setValue(content, "content");
}

等等。

然后我使用以下命令创建xml文件:

XMLCreator collection = new XMLCreator(docs);

File fileOut = new File("docs.xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(fileOut));
JAXBContext jaxbContext = JAXBContext.newInstance(XMLCreator.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(collection, writer);

它有效,但我希望我的xml文件具有以下格式:

<add>
    <doc>
        <field name="authors">Patrick Eagar</field>
        <field name="subject">Sports</field>
        <field name="dd">796.35</field>
        <field name="numpages">128</field>
        <field name="desc"></field>
        <field name="price">12.40</field>
        <field name="title">Summer of the all-rounder: Test and championship cricket in England 1982</field>
        <field name="isbn">0002166313</field>
        <field name="yearpub">1982</field>
        <field name="publisher">Collins</field>
    </doc>
    <doc>
        ...
    </doc>
</add>

我的目前如下:

<add>
    <doc id="2">
        <field></field>
        <field>Sugai, I.</field>
        <field></field>
        <field>CACM December, 1958 </field>
        <field>CA581202 JB March 22, 1978  8:29 PM </field>
        <field></field>
        <field>2    5   2
               2    5   2
               2    5   2
        </field>
        <field>Extraction of Roots by Repeated Subtractions for Digital 
               Computers </field>
    </doc>
</add>

我想要做的是在每个字段元素中添加name属性。这可以通过使用@Xml ...注释吗?

1 个答案:

答案 0 :(得分:-1)

如果你想使用attr和value,你需要复杂的元素和@XmlValue注释:

@XmlElement(name = "doc")
@XmlAccessorType(XmlAccessType.FIELD)
private List<Node> list;

@XmlElement(name = "field")
@XmlAccessorType(XmlAccessType.FIELD)
private Node node;

@XmlAccessorType(XmlAccessType.FIELD)
class Node {
@XmlAttribute(name= "name")
private String attr;

@XmlValue
private Srting value;
}