我有以下HTML片段:
String source = "<p>dsdds</p>"
+ "<ul class=\"some-class-name\">"
+ "<li>data</li>"
+ "<li><div><ul><li>data</li></ul></div></li>"
+ "</ul>"
+ "<p>data</p>"
+ "<ul>data</ul><div>data</div>";
我想要达到的目的是得到结果:
<ul class="some-class-name">
<li>data</li>
<li><div><ul><li>data</li></ul></div></li>
</ul>
到目前为止我尝试过:
String endTag = "</ul>";
int origin = source.indexOf("<ul class=\"some-class-name\">");
int currentFrom = origin;
int to = source.indexOf(endTag, currentFrom);
while (true) {
int curIndex = source.indexOf("<ul", currentFrom + 1);
if (curIndex > -1) {
currentFrom = curIndex;
to = source.indexOf(endTag, currentFrom);
} else {
to = source.indexOf(endTag, to);
break;
}
}
System.out.println(source.substring(origin, to + endTag.length()));
但我总是得到:
<ul class="some-class-name">
<li>data</li>
<li><div><ul><li>data</li></ul></div></li>
</ul>
<p>data</p>
<ul>data</ul>
任何人都可以帮我修复我的代码吗?或者提出另一种方法。
编辑: 请不要建议像Jsoup这样的内置库。
答案 0 :(得分:0)
幸运的是,您的片段是有效的XHTML,这意味着它是有效的XML。
XPath专门用于从XML中提取节点:
// Must have a single root in order to parse.
String input = "<div>" + source + "</div>";
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node)
xpath.evaluate("//ul[@class='some-class-name']",
new InputSource(new StringReader(input)),
XPathConstants.NODE);
StringWriter result = new StringWriter();
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(result));
String fragment = result.toString();
答案 1 :(得分:0)
你应该像这样使用jsoup: Java HTML Parser。
Document doc = Jsoup.parse(source);
Element e = doc.select("ul.some-class-name").first();
System.out.println(e);
结果:
<ul class="some-class-name">
<li>data</li>
<li>
<div>
<ul>
<li>data</li>
</ul>
</div></li>
</ul>