首页 > 解决方案 > 如何使用 xlink:href 序列化 xml 标签

问题描述

当你有这样的 xml 时:

<?xml version="1.0" encoding="UTF-8"?>
<gml:FeatureCollection>
    <gml:featureMember>
        <imkl:Foo gml:id="Foo_1">
            <imkl:Bar xlink:href="Bar_1"/>
            <key>valueFoo</key>
        </imkl:Foo>
    </gml:featureMember>
    <gml:featureMember>
        <imkl:Bar gml:id="Bar1">
            <key>valueBar</key>
        </imkl:Bar>
    </gml:featureMember>
</gml:FeatureCollection>

其中Foo标签包含一个Bar带有xlink:href属性的标签,该属性指向一个标签,该标签实际上包含需要解析的标签。如何告诉杰克逊使用这个?

杰克逊是否支持开箱即用,还是我必须手动解析?

我试过了:

酒吧类

import javax.persistence.Id;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;

public class Bar{

   @Id
   @XmlID
   @XmlElement
   private String id; //should be "Bar_1"

   private String key; //should be "valueBar"

   ...
}

Foo 类

import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlIDREF;

public class Foo{

   @Id
   @XmlID
   @XmlElement
   private String id; //should be "Foo_1"

   private String key; //should be "valueFoo"

   @XmlIDREF
   @XmlElement(name = "Bar")
   private Bar bar; //Should be Bar with id "Bar_1" and key with "valueBar"

   ...
}

标签: javaxmljacksonjaxb

解决方案


如果我理解正确,你想解析内部属性,如果是这样,你可以简单地使用XmlAttribute

 public static void main(String[] args) throws IOException {
    XmlMapper mapper = new XmlMapper();
    // Simplified XML
    String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "    <GebiedsinformatieLevering id=\"nl.imkl-KA0000._GebiedsinformatieLevering_19O081120-1\">\n" +
            "        <belanghebbende href=\"nl.imkl-KL1011._Belanghebbende_19O081120-1\"/>\n" +
            "    </GebiedsinformatieLevering>";
    GebiedsinformatieLevering levering = mapper.readValue(str.getBytes(), GebiedsinformatieLevering.class);
    System.out.println(levering.getBelanghebbende().getHref());
}

public static class Belanghebbende {
    @XmlAttribute
    private String href;

    // getters & setters
}

public static class GebiedsinformatieLevering {
    private String text;

    @XmlIDREF
    @XmlElement(name = "belanghebbende")
    private Belanghebbende belanghebbende;

    @XmlID
    @XmlElement
    private String id;

    // getters & setters
}

}

输出:

nl.imkl-KL1011._Belanghebbende_19O081120-1

或者您是否需要此链接作为另一个条目的标识符?

<imkl:Belanghebbende gml:id="nl.imkl-KL1011._Belanghebbende_19O081120-1">

推荐阅读