1

结构

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

   </table>
</html>

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

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

解组为 null。

4

2 回答 2

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'
于 2013-07-12T11:08:42.823 回答
0

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

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);
    }

}
于 2013-07-12T11:15:01.597 回答