2

现在我的软件将显示来自 xml 文件的(根元素:数据),但我需要节点列表。这是 Xml 文件所拥有的,例如:

(数据有“count”和“person”)

(计数 = 1)

(人有“名字”和“汽车”)

(名字=“亚当”)

(汽车有“Porshe”和“minimini”)

软装

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public void Ada()
{
File fXmlFile = new File("c:\\file.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
}

XML 文件:

<data>
    <count>1</count>
    <person>
        <name>Adam<name>
        <cars>
            <fast>Porshe</fast>
            <slow>MiniMini</slow>
        </cars>
    </person>
</data>
4

2 回答 2

3

您可以使用:

doc.getChildNodes()

深入并递归钻取,直到没有孩子。

它将返回一个NodeList你可以使用size()'power'一个for循环。

于 2012-11-04T15:04:49.657 回答
1

看看 XPath:http: //developer.android.com/reference/javax/xml/xpath/package-summary.html

您基本上可以使用它在 Android 上使用 XML 做任何您需要的事情。

所以像:

XPath x = XPathFactory.newInstance().newXPath();
String expression = "/data";
InputSource source = new InputSource("someXML.xml");
NodeSet nodes = (NodeSet)xpath.evaluate(expression, source, XPathConstants.NODESET);

那应该给你一个节点的 NodeSet。

希望有帮助。

于 2012-11-04T15:10:06.367 回答