我有一个xml标签你好,我的java中有一个如下所示的字段
class HelloWorld{
@XmlElement
private String name;
}
虽然解组这成功地将 Hello 值分配给名称变量。现在我想从我正在为其进行编组的这个 java 对象(HelloWorld)创建一个新的 xml,但在这种情况下,我想要一个 xml 标记而不是在我的 xml 中。我怎样才能在 Jaxb 中实现这一点?
两个 Xml 都不在我的控制范围内,所以我无法更改标签名称
编辑:
传入 XML - helloworld.xml
<helloworld>
<name>hello</name>
</helloworld>
@XmlRootElement(name="helloworld)
class HelloWorld{
@XmlElement(name="name")
private String name;
// setter and getter for name
}
JaxbContext context = JAXBContext.newInstance(HelloWorld.class);
Unmarshaller un = conext.createUnmarshaller un();
HelloWorld hw = un.unmarshal(new File("helloworld.xml"));
System.out.println(hw.getName()); // this will print hello as <name> tag is mapped with name variable.
现在我想使用 HelloWorld 对象的这个 hw 对象来创建一个如下所示的 xml
<helloworld>
<name_1>hello</name_1> // Note <name> is changed to <name_1>
</helloworld>
我不想创建另一个像 Helloworld 这样的类并在该新类中声明一个变量 name_1。我只想重用这个 HelloWorld 类,因为只是更改了一个标签名称。
但我使用现有的 HelloWorld 类并尝试编组对象硬件,如下所示
JaxbContext context = JAXBContext.newInstance(HelloWorld.class);
Marshaller m = conext.createMarshaller();
StringWriter writer = new StringWriter();
m.marshal(hw,writer);
System.out.println(writer.toString());
这将打印如下
<helloworld>
<name>hello</name>
</helloworld>
但我需要
<helloworld>
<name_1>hello</name_1> // Note <name> is changed to <name_1>
</helloworld>
原因是解组前传入的 xml 和编组后传出的 xml 不在我的控制之下。
希望这能解释。