有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析从网站到Android设备的XML

我正在启动一个Android应用程序,它将解析web上的XML。我已经创建了一些Android应用程序,但它们从未涉及解析XML,我想知道是否有人有关于最佳方式的建议


共 (5) 个答案

  1. # 1 楼答案

    我会使用DOM解析器,如果XML文件不太大,它的效率不如SAX,因为在这种情况下更容易

    我只制作了一个android应用程序,涉及XML解析。从SOAP web服务接收的XML。我使用了XmlPullParser。该实现来自Xml。newPullParser()有一个错误,对nextText()的调用并不总是像文档承诺的那样提前到END_标记。有一个解决办法

  2. # 2 楼答案

    下面是一个例子:

            try {
                URL url = new URL(/*your xml url*/);
                URLConnection conn = url.openConnection();
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(conn.getInputStream());
    
                NodeList nodes = doc.getElementsByTagName(/*tag from xml file*/);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    NodeList title = element.getElementsByTagName(/*item within the tag*/);
                    Element line = (Element) title.item(0);
                    phoneNumberList.add(line.getTextContent());
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
    

    在我的示例中,我的XML文件看起来有点像:

    <numbers>
       <phone>
          <string name = "phonenumber1">555-555-5555</string>
       </phone>
       <phone>
          <string name = "phonenumber2">555-555-5555</string>
       </phone>
    </numbers>
    

    我会用“phone”替换/*tag from xml file*/,用“string”替换/*item within the tag*/

  3. # 3 楼答案

    我总是使用w3c dom类。我有一个静态助手方法,我使用它将xml数据解析为字符串,并向我返回一个文档对象。获取xml数据的位置可能会有所不同(web、文件等),但最终会将其作为字符串加载

    像这样的

        Document document = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
    
        try
        {
            builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(data));
            document = builder.parse(is);
        }
        catch (SAXException e) { }
        catch (IOException e) { }
        catch (ParserConfigurationException e) { }
    
  4. # 5 楼答案

    我知道有三种类型的解析:DOM、SAX和XMLPullParsing

    在我这里的示例中,您需要XML元素的URL和父节点

    try {
        URL url = new URL("http://www.something.com/something.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();
    
        NodeList nodeList1 = doc.getElementsByTagName("parent node here");
        for (int i = 0; i < nodeList1.getLength(); i++) {
            Node node = nodeList1.item(i);
        }
    } catch(Exception e) {
    
    }
    

    也可以试试this