JAXB应该忽略元素

时间:2013-07-12 10:39:50

标签: jaxb unmarshalling

结构

<html>
   <span><h1>test</h1></span>
   <table>

   </table>
</html>

如果<span>可能是<div>,我如何才能获得“测试”文字?

@XmlAccessorType(XmlAccessType.FIELD)
public class HtmlTag {
    @XmlElement(name = "h1")
    String h1;
}

Unmarshalls为null。

2 个答案:

答案 0 :(得分:1)

@XmlAccessorType(XmlAccessType.FIELD)
public class HtmlTag 
{
    @XmlAnyElement
    List<org.w3c.dom.Element> elements;
}  

获取test字符串

HtmlTag htmlTag = //...  
Element firstElement = htmlTag.elements.get(0); // this is first element,
                                        // currently it is <span>
firstElement.getElementsByTagName("h1").item(0).getTextContent(); // return 'test'

答案 1 :(得分:0)

您可以在StreamFilter上使用StAX XMLStreamReader,以便您要忽略的元素不会报告为事件。然后,您可以使用JAXB从XMLStreamReader解组。

import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(HtmlTag.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        StreamSource xml = new StreamSource("src/forum17613060/input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(xml);
        xsr = xif.createFilteredReader(xsr, new StreamFilter() {

            @Override
            public boolean accept(XMLStreamReader reader) {
                if(reader.isStartElement() || reader.isEndElement()) {
                    String localName = reader.getLocalName();
                    return !"span".equals(localName) && !"div".equals(localName);
                }
                return true;

            }

        });

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        HtmlTag htmlTag = unmarshaller.unmarshal(xsr, HtmlTag.class).getValue();
        System.out.println(htmlTag.h1);
    }

}