我正在尝试解析XML文件,但是我在修复我收到的错误时遇到了一些麻烦

时间:2013-05-03 07:49:24

标签: java android eclipse xml-parsing

我一直在试图弄清楚如何解决在尝试解析XML文件时我收到的错误。

这是我的MainActivity.java文件:

package com.example.android;

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

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.renderscript.Element;
import android.util.Log;
import android.view.Menu;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

    String playerId,
           playerPd,
           playerType,
           xml;
    DefaultHttpClient httpClient;
    HttpPost httpPost;
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    Document doc;
    DocumentBuilderFactory dbf;
    DocumentBuilder db;
    InputSource inputSource;
    NodeList n,
             nl;
    Node child;
    XmlPullParser parser;
    static final String URL = ".xml URL WITHELD";
    static final String PLAYERS = "Players"; //parent node
    static final String PLAYER_PD = "PlayerPD";
    static final String PLAYER_TYPE = "PlayerType";     

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public String getXmlFromUrl(String url){
        xml = null;
        try{
            //defaultHttpClient
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost (url);

            httpResponse = httpClient.execute(httpPost);
            httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);         
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        //return XML
        return xml; 
    }

    public Document getDomElement(String xml){
        doc = null;
        dbf = DocumentBuilderFactory.newInstance();
        try{
            db = dbf.newDocumentBuilder();

            inputSource = new InputSource();
            inputSource.setCharacterStream(new StringReader (xml)); 
            doc = db.parse(inputSource);
        } catch (ParserConfigurationException e) {
            Log.e("Error: ",e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ",e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ",e.getMessage());
            return null;
        } 
        //return DOM
        return doc;     
    }

    public String getValue(Element item, String str){
        n = ((Document) item).getElementsByTagName(str);
        return this.getElementValue(n.item(0));     
    }

    private final String getElementValue(Node elem){
        // TODO Auto-generated method stub
        if(elem.hasChildNodes()){
            for(child = elem.getFirstChild(); child != null; child = child.getNextSibling()){
                if(child.getNodeType() == Node.TEXT_NODE){
                    return child.getNodeValue();
                }
            }
        }
        return null;        
    }


   public void parseXml(){

      xml = parser.getXmlFromUrl(URL); //Getting XML

在这一行,第149行,我收到一条错误,上面写着“方法getXmlFromUrl(String)未定义类型XmlPullParser”

      doc = parser.getDomElement(xml); //Getting DOM element

并且,在这一行,第150行,我收到一条错误,上面写着“方法getDomElement(String)未定义类型XmlPullParser”

      nl = doc.getElementsByTagName(PLAYERS);

      for (int i = 0; i < nl.getLength(); i++){
      playerPd = parser.getValue(e, PLAYER_PD); //PlayerPD child value

此外,在这一行以及随后的一行,第155行和第156,我收到一条错误,上面写着“e无法解析为变量”

      playerType = parser.getValue(e, PLAYER_TYPE); //Player Type child value
}

}
}

如果这有帮助,我试图解析的XML文件的布局是这样的:

-<Players>
  -<Player id="">
    <PlayerType></PlayerType>
   </Player>
 </Players>

任何帮助将不胜感激,并提前感谢。

1 个答案:

答案 0 :(得分:3)

删除parser.

public void parseXml(){

      xml = getXmlFromUrl(URL); //Getting XML

或者您可以创建一个类XMLParser并在新类中添加getXmlFromUrl函数

与其他功能类似

doc = getDomElement(xml); //Getting DOM element

你的线路155&amp; 156不在完整的源代码中,所以我不确定上下文。


所以你已经提到了原始教程。本教程的含义是您需要创建一个包含名为XMLParser.java

的新类的新文件XMLParser
public class XMLParser {
}

然后慢慢地向该类添加函数

public class XMLParser {
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }
}

等等,将其他函数添加到类中。然后,您可以使用MainActivity课程中的课程。


至于e cannot be resolved to a variable,网页上有一条缺失的行。

NodeList nl = doc.getElementsByTagName(KEY_ITEM);

// looping through all item nodes <item>     
for (int i = 0; i < nl.getLength(); i++) {
    Element e = (Element)nl.item(i); // >>> the missing line in the sample <<<
    String name = parser.getValue(e, KEY_NAME); // name child value
    String cost = parser.getValue(e, KEY_COST); // cost child value
    String description = parser.getValue(e, KEY_DESC); // description child value
}