我有一个huuge HTML文件,像这样:
<html>
<head>
</head>
<body>
<div id="wraper">
<div id="..."> </div>
<div id="..."> </div>
<div id="..."> </div>
<div class="col x8 black">
<div class="sidebar">
<script .../>
<script .../>
<div class="side-box last10">
<h3 .../>
<ul class="sidebarlist">
<li class="fisrt"> Need this Text </li>
<li> Need this Text too (1) </li>
<li> Need this Text too (2) </li>
</ul>
</div>
</div
</div>
</body>
如何在此html文件中“导航”以获取我想要的文本?
html->body->div#wraper->div#col x8 black-> div#side-vox last10-> ul#sidebarlist -> li#first
对于这项工作,什么是更好的DOM或SAX? (我不是母语为英语的人)
答案 0 :(得分:1)
你可以XmlPullParser这样做。请仔细阅读以下代码:
public void parsing(String str1) throws XmlPullParserException, IOException{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader (str1));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String str;
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
str = xpp.getName();
System.out.println("Start tag "+str);
if(xpp.getName().equals("div")){
int attrCount = xpp.getAttributeCount();
if(attrCount != -1) {
for(int x=0;x<attrCount;x++) {
System.out.println("Attr Name= "+ xpp.getAttributeName(x));
System.out.println("Attr Value= "+ xpp.getAttributeValue(x));
}
}
}
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Value= "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
}
答案 1 :(得分:1)
你考虑过XPath吗?你的伪代码:
html->body->div#wraper->div#col x8 black-> div#side-vox last10->
ul#sidebarlist -> li#first
...直接转换为以下XPath表达式:
/html/body/div[@id='wraper']/div[@class='col x8 black']/
div[@class='side-vox last10']/ul[@class='sidebarlist']/li[@class='fisrt']
或者,更简洁(假设您的示例中的结构具有代表性):
/html/body/div[1]/div[4]/div[1]/div[1]/ul[1]/li[1]
有关在Android上使用XPath的信息,请访问: