如何用多个节点解析XML?

时间:2012-06-20 08:01:29

标签: android

我想简单地使用任何解析方法解析XML;我有以下格式的XML。

以下是我的XML示例。我尝试使用DOM Parser,但我没有成功:

 <Main>
      <name> 
          <firstname>ABC</firstname>
          <lastname>XYZ</lastname>
     </name>
   <address>
      <homeaddress>
              <pobox>PQR</pobox>
               <city>MNQ</city>
       </homeaddress>
       <officeaddress>      
               <pobox>JKL</pobox>
               <city>URI</city>
            </officeaddress>
     </address>
  <Main>

1 个答案:

答案 0 :(得分:1)

我告诉你我解析数据的方式;希望你能在你的实施中实现。

<强> allClientParser.java

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class allClientParser {

    public Client parseByDOM(String response)
            throws ParserConfigurationException, SAXException, IOException {

        Client c = new Client();

        try {

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

            Document doc = dBuilder.parse(new InputSource(new StringReader(
                    response)));
            doc.getDocumentElement().normalize();
            NodeList nList = doc.getElementsByTagName("row");

            c.length = nList.getLength();
            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    c.clientdata[temp][1] = getTagValue("client_id", eElement);
                    c.clientdata[temp][2] = getTagValue("name", eElement);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return c;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
                .getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();
    }
}

<强> Client.java

public class Client {

    public int length;
    public String clientdata[][] = new String[500][500];
}

现在从main方法我们只需通过将XML作为字符串传递给它来调用它::

Client abc;
allClientParser cl=new allClientParser();
abc=cl.parseByDOM(pass your xml as String here);

现在您可以像这样访问您的数据::

String name=abc.clientdata[x][y];