如何解析android中的本地XML文件?
问题描述:
我正在开发一个android项目,我无法解析本地文件(raw/file.xml)。我尝试了一些我在互联网上找到的建议,但徒劳无功。 它工作时,我尝试解析网络中的文件(使用URL类...),但当我尝试使用本地文件程序不起作用!请我需要帮助。 (我用萨克斯作为XML解析器)如何解析android中的本地XML文件?
我更换线URL sourceUrl = new URL ("example.com/w...";);
与InputSource is = new InputSource(getResources().openRawResource(R.raw.example));
和线xr.parse(new InputSource(sourceUrl.openStream()));
与xr.parse(new InputSource(is.getByteStream()));
答
You can put the xml file path here and keep parsing the inner nodes usiln self running loop. Save the values in arrays accordingly for each node..
NodeList eNodeList = null;
eNodeList = Utils.getXMLFromFilePath(your.xml", "firstNOdeNAme", eNodeList);
getElementsByNodelist(eNodeList)
private static getElementsByNodelist(Nodelist nodelist)
{
if(nodelist!=null)
{
for(int i = 0;i<nodelist.getLength();i++)
{
Element element = (Element) nodelist.item(i);
String id=getTextValue(element, "id");
//For attribute value
element.getAttribute("attributename");
// if u want to parse tjis element again
NodeList l=element.getElementsByTagName("innerTag");
// self loop
getElementsByNodelist(l);
}
}
}
public static String getTextValue(Element ele, String tagName) {
String textVal = "";
NodeList nl = ele.getElementsByTagName(tagName);
if(nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
if(el.getFirstChild()!=null)
{
textVal = el.getFirstChild().getNodeValue();
}
}
return textVal;
}
它不工作?精心设计,会发生什么。 – 2012-07-10 13:55:00
我替换行 URL sourceUrl = new URL(“http://www.example.com/w ...”); 与 InputSource is = new InputSource(getResources()。openRawResource(R.raw.example)); 和行 xr.parse(new InputSource(sourceUrl.openStream())); 与 xr.parse(new InputSource(is.getByteStream())); – giusepe 2012-07-10 14:01:17
@ user1514941,您的评论是不可读的,请编辑您的问题添加这些代码行,或者如果可能的话,整个应用程序代码。 – Egor 2012-07-10 14:10:05