我已经创建了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>
因此,在这个例子中,我丢失头标签。 有什么办法让编组工作变得更聪明一点?
所以,如果你解组这个文件,然后马上再次对象,它会删除所有的值?这听起来好像你没有正确解析XML文件。 –
我已更新我的问题 – matyyyy