问题描述
我创建了打开一个看起来像这样的XML文件Java应用程序:
I created a Java application which opens an xml file that looks something like this:
<AnimalTree>
<animal>
<mammal>canine</mammal>
<color>blue</color>
</animal>
<!-- ... -->
</AnimalTree>
我可以使用打开它:
And I can open it using:
File fXmlFile = getResources.getXml("res/xml/data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList animalNodes = doc.getElementsByTagName("animal");
然后,我可以简单地创建一个节点,对象推入一个ListArray,然后做我想做的对象为通过ListArray我循环。
Then I can simply create a node, push the object into a ListArray, then do what I want with the objects as I loop through the ListArray.
for (int temp = 0; temp < animalNodes.getLength(); temp++) {
Node nNode = animalNodes.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
question thisAnimal = new animal();
thisAnimal.mammal = getTagValue("mammal",eElement);
// ...
平原和简单!现在只有在Android的我不能简单地读取文件 RES / XML / data.xml中
,因为文件();
要求字符串
不是整数
(ID)。这是我很失落。有一些办法可以让文件();
打开文件,或者这是不可能的,而无需使用的SAXParser
或 XPP
? (这两个我实在无法理解,不管我怎么努力。)
如果我被迫使用这些方法,可以有人告诉我一些简单的code类似于我的例子?
Plain and simple! Now only, in Android I cannot simply read the file "res/xml/data.xml
" because "File();
" requires a String
not an integer
(id). This is where I am lost. Is there some way I can make "File();
" open the file, or is this impossible without using SAXparser
or XPP
? (both of which I really cannot understand, no matter how hard I try.)
If I am forced to use those methods, can someone show me some simple code analogous to my example?
推荐答案
如果它在资源树,它会得到分配给它的ID,这样你就可以打开一个流,它与openRawResource功能:
If it's in the resource tree, it'll get an ID assigned to it, so you can open a stream to it with the openRawResource function:
的InputStream是= context.getResources()openRawResource(R.xml.data);
对于使用XML在Android的工作,此链接ibm.com 是令人难以置信彻底。
As for working with XML in Android, this link on ibm.com is incredibly thorough.
请参阅清单9.基于DOM实现饲料解析器
的该链接。
一旦你的输入流(上图),你可以把它传递给的DocumentBuilder实例:
Once you have the input stream (above) you can pass it to an instance of DocumentBuilder:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.getInputStream());
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("TheTagYouWant");
请记住,我没有这样做个人 - 我假设由IBM工作提供的code。
Keep in mind, I haven't done this personally -- I'm assuming the code provided by IBM works.
这篇关于从RES / XML在Android开放XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!