Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 封送字段作为具有字段';姓名_Java_Xml_Jaxb - Fatal编程技术网

Java 封送字段作为具有字段';姓名

Java 封送字段作为具有字段';姓名,java,xml,jaxb,Java,Xml,Jaxb,某个地方的一位聪明人设计了如下xml: <node> <subnode value="sv1"/> <anotherSubNode value="asv" /> </node> class Node { String subnode; String anotherSubNode; //... } 而不是 class NodeValue { @XmlAttribute String value; } class Nod

某个地方的一位聪明人设计了如下xml:

<node>
  <subnode value="sv1"/>
  <anotherSubNode value="asv" />
</node>
class Node {
  String subnode;
  String anotherSubNode;
  //...
}
而不是

class NodeValue {
  @XmlAttribute
  String value;
}
class Node {
  NodeValue subnode;
  NodeValue anotherSubNode;
  /...
}
有没有一种方法可以通过标准的JavaXML封送有效地实现这一点?甚至非标准?

An是最简单、最通用的解决方案。字符串字段的适配器如下所示:

public class NodeValueStringAttrMarshaller extends XmlAdapter<NodeValueElement, String> {

    @Override
    public NodeValueElement marshal(String v) throws Exception {
        return new NodeValueElement(v);
    }

    @Override
    public String unmarshal(NodeValueElement v) throws Exception {
        if (v==null) return "";
        return v.getValue();
    }

}
要使用适配器,必须在POJO中注释适当的字段:

class Node {
  @XmlJavaTypeAdapter(value=NodeValueStringAttrMarshaller.class)
  String subnode;

  @XmlJavaTypeAdapter(value=NodeValueLongAttrMarshaller.class)
  Long anotherSubNode;
  //...
}
A是最简单、最通用的解决方案。字符串字段的适配器如下所示:

public class NodeValueStringAttrMarshaller extends XmlAdapter<NodeValueElement, String> {

    @Override
    public NodeValueElement marshal(String v) throws Exception {
        return new NodeValueElement(v);
    }

    @Override
    public String unmarshal(NodeValueElement v) throws Exception {
        if (v==null) return "";
        return v.getValue();
    }

}
要使用适配器,必须在POJO中注释适当的字段:

class Node {
  @XmlJavaTypeAdapter(value=NodeValueStringAttrMarshaller.class)
  String subnode;

  @XmlJavaTypeAdapter(value=NodeValueLongAttrMarshaller.class)
  Long anotherSubNode;
  //...
}