使用JAXB更新XML模板文件

时间:2015-07-21 16:17:21

标签: java xml jaxb eclipselink

我创建了XML文件让我们称之为template.xml。它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<html>
   <head>
    <title>TITLE</title>
   </head>
   <body>
      <div>
         <section/>
         <section>
            <p>section1</p>
         </section>
         <section>
            <p>section2</p>
         </section>
         <table/>
      </div>
   </body>
</html>

现在我&#39; d喜欢tu unmarshall template.xml并只更改specyfic标签的内容。

我想要做的是以与XSL类似的方式使用JAXB mashaller。我想拥有我的模板文件,然后只更改specyfic标签。我尝试使用EclipseLink XMLPath创建模型

package html.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="html")
public class Html {


    @XmlPath("body/div")
    private Div div;

    public Div getDiv() {
        return div;
    }

    public void setDiv(Div div) {
        this.div = div;
    } 



}

我的程序如下:

public class Updater {

    public static void main(String[] args) {
        try{
            File file = new File("html_example.xml");
            JAXBContext jc =  JAXBContext.newInstance(Html.class);
            Unmarshaller jaxbUnmarshaller = jc.createUnmarshaller();
            Html html = (Html) jaxbUnmarshaller.unmarshal(file);

            Div div = html.getDiv();
            Section section = div.getSection();
            section.setName("UPDATED VALUE");


            Marshaller jaxbMarshaller = jc.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            jaxbMarshaller.marshal(html, new File("html_example.xml"));


        } catch (JAXBException e) {e.printStackTrace();}
    }

但我的输出是:

<?xml version="1.0" encoding="UTF-8"?>
<html>
   <body>
      <div>
         <section>
            <p>Jemmy_test</p>
         </section>
         <section>
            <p>UPDATED VALUE</p>
         </section>
         <table/>
      </div>
   </body>
</html>

所以在这个例子中我失去了头部标签。 有没有办法让marshaller工作更聪明一点?

1 个答案:

答案 0 :(得分:0)

问题是你没有将头部元素映射到任何东西,因此当你取消对xml的删除它只会丢弃它。编组对象会创建一个不知道元素的新文件。

如果您希望再次输出所有元素,则需要对xml中的所有元素进行建模。您可以从xhtml架构生成所有模型,虽然这会为您做很多繁重的工作。