java对象中XML键值对的解组

使用 jaxb 将 XML 键值部分解组为 java 对象。我尝试过使用地图适配器,但无法做到这一点。


<ACCOUNT_CHANGES>

    <TYPE value="Active" />

    <RECORD>

        <SUBSCRIPTION>

            <INFO key="aaa">

                <![CDATA[042]]>

            </INFO>

            <INFO key="bbb">

                <![CDATA[45]]>

            </INFO>

            <INFO key="uuid">

                <![CDATA[d9a7e94c-0a9d-c745-82e9-980877cc5043]]>

            </INFO>

            <INFO key="ccc">

                <![CDATA[Active]]>

            </INFO>

            <INFO key="companyname">

                <![CDATA[ltd]]>

            </INFO>

        </SUBSCRIPTION>

    </RECORD>

</ACCOUNT_CHANGES>  


慕田峪7331174
浏览 81回答 1
1回答

ABOUTYOU

您可以使用适配器来做到这一点,但据我了解您的要求,这是没有必要的。如果您只是想解组为对象而不是 Map,则可以执行以下操作:从根开始:@XmlRootElement(name = "ACCOUNT_CHANGES")@XmlAccessorType(XmlAccessType.FIELD)public class AccountChanges {&nbsp; &nbsp; @XmlElement(name = "TYPE")&nbsp; &nbsp; private Type type;&nbsp; &nbsp; @XmlElement(name = "RECORD")&nbsp; &nbsp; private Record record;}让我们把 Type 去掉:@XmlAccessorType(XmlAccessType.FIELD)public class Type {&nbsp; &nbsp; @XmlAttribute&nbsp; &nbsp; private String value;}然后记录一下:@XmlAccessorType(XmlAccessType.FIELD)public class Record {&nbsp; &nbsp; @XmlElement(name = "SUBSCRIPTION")&nbsp; &nbsp; private Subscription subscription;}以及订阅:@XmlAccessorType(XmlAccessType.FIELD)public class Subscription {&nbsp; &nbsp; @XmlElement(name = "INFO")&nbsp; &nbsp; private List<Info> infoList;}信息将您的键作为属性,然后是一些值。它看起来像这样:@XmlAccessorType(XmlAccessType.FIELD)public class Info {&nbsp; &nbsp; @XmlAttribute&nbsp; &nbsp; private String key;&nbsp; &nbsp; @XmlValue&nbsp; &nbsp; private String value;&nbsp; &nbsp; public String getKey() {&nbsp; &nbsp; &nbsp; &nbsp; return key;&nbsp; &nbsp; }&nbsp; &nbsp; public String getValue() {&nbsp; &nbsp; &nbsp; &nbsp; return value;&nbsp; &nbsp; }}这将解组您的 xml,并且信息键和值将位于字段中。如果您想要映射中的键和值,可以使用适配器。适配器看起来像这样:public class MyMapAdapter extends XmlAdapter<Info, Map<String, String>> {&nbsp; &nbsp; private HashMap<String, String> hashMap = new HashMap<String, String>();&nbsp; &nbsp; @Override&nbsp; &nbsp; public Map<String, String> unmarshal(Info v) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; hashMap.put(v.getKey(), v.getValue());&nbsp; &nbsp; &nbsp; &nbsp; return hashMap;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public Info marshal(Map<String, String> v) throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; // do here actions for marshalling if u also marshal&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}您将更改订阅以使用适配器并将地图作为字段:@XmlAccessorType(XmlAccessType.FIELD)public class Subscription {&nbsp; &nbsp; @XmlElement(name = "INFO")&nbsp; &nbsp; @XmlJavaTypeAdapter(MyMapAdapter.class)&nbsp; &nbsp; private Map<String, String> infoMap;}有两种方法,都可以解组您的 xml 有效负载。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java