内部文本和子元素

时间:2011-05-12 16:22:19

标签: java xml jaxb

我想在Java中使用JAXB反序列化XML,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <container>
        inner text that I need
        <foo attrib="meh">
            <bar>value</bar>
        </foo>
    </container>
</root>

绊倒我的是抓住<container>的内部文本:我不能同时使用@XmlValue获取内部文本而@XmlElement同时抓住foo元素来自内心文本。请参阅下文,了解我要做的事情

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;

public class App {

    private static final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><container>text<foo attrib=\"meh\"><bar>waffles</bar></foo></container></root>";

    @XmlRootElement(name = "foo") static class Foo {
        @XmlAttribute public String attrib;
        @XmlElement   public String bar;
    }

    @XmlRootElement(name = "container") static class Container {
        //@XmlValue   public String innerText;
        @XmlElement public Foo foo;
    }

    public static void main(String[] args) {
        try {
            final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
            final XMLEventReader xer = xmlInputFactory.createXMLEventReader(new ByteArrayInputStream(xml.getBytes("UTF-8")));

            XMLEvent evt = xer.nextEvent(); // start document
            evt = xer.nextEvent(); // <root>
            evt = xer.peek(); // advance to <container>

            JAXBContext ctx = JAXBContext.newInstance(Container.class);
            Unmarshaller um = ctx.createUnmarshaller();
            Object o = um.unmarshal(xer);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XMLStreamException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

1 个答案:

答案 0 :(得分:4)

这被称为“混合模式内容”,通常是处理屁股的痛苦。

JAXB中的关键是使用@XmlMixed注释 - 请参阅javadoc

尝试这样的事情:

@XmlRootElement(name = "container") 
static class Container {
    @XmlMixed 
    @XmlElementRefs({
            @XmlElementRef(name="foo", type=Foo.class)
    })
    List<?> content;

    // ... plus the usual getters/setters
}

content列表应包含一系列Foo个对象和字符串。