有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用JAXB更新java XML模板文件

我已经创建了XML文件,我们称之为模板。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>

现在我想要一个模板。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>

所以在这个例子中,我松开了头部标签。 有没有办法让马歇尔的工作更聪明一点


共 (1) 个答案

  1. # 1 楼答案

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

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