1
我必須解析此XML https://i.imgur.com/GUAHB4t.jpg以提取「DetailPageURL」標記下的突出顯示的字符串。我做了一個嘗試,但有很混亂的想法。我正在開發Android SDK使用Android和Java解析XML
import android.os.AsyncTask;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class ReflinkFetcher extends AsyncTask<String, Void, String> {
String refLink = null;
@Override
protected String doInBackground(String... url){
Document doc = openXML(url[0]);
Element rootElement = doc.getDocumentElement();
refLink = getString("DetailPageUrl", rootElement);
return refLink;
}
public String getRefLink(){
return refLink;
}
private Document openXML(String url) {
Document doc = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new URL(url).openStream());
} catch (SAXException e1) {
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
} catch (MalformedURLException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
return doc;
}
private String getString(String tagName, Element element) {
NodeList list = element.getElementsByTagName("Items");
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes(); //0=items
if (subList != null && subList.getLength() > 0) {
subList = subList.item(4).getChildNodes(); //4=item
if(subList != null && subList.getLength() >0) {
subList = subList.item(2).getChildNodes(); //2=DetailPageURL
if(subList != null && subList.getLength() >0) {
return subList.item(0).getNodeValue(); // Value??
}
}
}
}
return null;
}
}
最終返回null正在執行。我認爲「getString」方法也很差。我該如何改進它?
我建議您閱讀有關Retrofit和簡單的XML轉換器 – DeKaNszn
這個普通的問題已經回答了許多其他時間 - 例如, https://stackoverflow.com/questions/340787/parsing-xml-with-xpath-in-java 那裏給出的解決方案使用XPath,我認爲這將是解決這個特定問題的理想解決方案。 – Squiggle
[在Java中使用XPath解析XML]可能的副本(https://stackoverflow.com/questions/340787/parsing-xml-with-xpath-in-java) – Squiggle