1

我有一个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 不在我的控制之下。

希望这能解释。

4

1 回答 1

0

选项 #1 - 适用于所有 JAXB 实现

您可以使用 XSLT 转换将 aJAXBSource转换为您想要的 XML:

    // Create Transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    StreamSource xslt = new StreamSource(
            "src/blog/jaxbsource/xslt/stylesheet.xsl");
    Transformer transformer = tf.newTransformer(xslt);

    // Source
    JAXBContext jc = JAXBContext.newInstance(Library.class);
    JAXBSource source = new JAXBSource(jc, catalog);

    // Result
    StreamResult result = new StreamResult(System.out);

    // Transform
    transformer.transform(source, result);

了解更多信息


选项 #2 - 与EclipseLink JAXB (MOXy)一起使用

注意: 我是 MOXy 领导。

MOXy 提供了一个映射文档扩展,您可以使用它来覆盖字段/属性级别的映射。这意味着您可以JAXBContext仅在注释上创建一个,然后JAXBContext基于带有 XML 覆盖的注释创建第二个。

了解更多信息

于 2014-01-21T18:18:18.943 回答