结构
<html>
<span><h1>test</h1></span>
<table>
</table>
</html>
如果<span>
可能是,我如何获得文本“测试” <div>
?
@XmlAccessorType(XmlAccessType.FIELD)
public class HtmlTag {
@XmlElement(name = "h1")
String h1;
}
解组为 null。
结构
<html>
<span><h1>test</h1></span>
<table>
</table>
</html>
如果<span>
可能是,我如何获得文本“测试” <div>
?
@XmlAccessorType(XmlAccessType.FIELD)
public class HtmlTag {
@XmlElement(name = "h1")
String h1;
}
解组为 null。
@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'
StreamFilter
您可以在 an 上利用 StAX ,XMLStreamReader
以便您要忽略的元素不会报告为事件。然后你可以从XMLStreamReader
with 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);
}
}