2015-07-21 77 views
0

我已经创建了XML文件我们称之为template.xml。它看起来像这样:使用JAXB更新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> 

现在我想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> 

因此,在这个例子中,我丢失头标签。 有什么办法让编组工作变得更聪明一点?

+0

所以,如果你解组这个文件,然后马上再次对象,它会删除所有的值?这听起来好像你没有正确解析XML文件。 –

+0

我已更新我的问题 – matyyyy

回答

0

问题是你没有将头元素映射到任何东西,所以当你解开它只是丢弃它的XML。编组对象会创建一个不知道元素的新文件。

如果您希望再次输出所有元素,您将需要对xml中的所有元素建模。您可以从xhtml模式生成所有模型,但它会为您做很多繁重的工作。

+0

是的,我知道如果我使用所有标记创建模型,它将起作用。问题是我不想要这个。在我的模板中会有很多不同的标签,也有很多不同的标签。对于我来说,创建只能访问specyfic标签的模型会更方便和更易读。 – matyyyy