【问题标题】:How to Parse XML file Using Dom Parsing?如何使用 Dom Parsing 解析 XML 文件?
【发布时间】:2012-08-24 09:06:09
【问题描述】:

我的问题是我正在使用 Dom Parsing 来解析下面的 xml 文件,但这给了我 NullPointerException 的错误。

任何帮助将不胜感激。

MainActivity.java

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScrollView mScrView1 = new ScrollView(this);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);

        /** Create a new textview array to display the results */
        TextView id[];
        TextView published[];
        TextView content[];
        TextView title[];

        TextView mediacontent[];
        TextView mediathumbnail[];

        try {

            URL url = new URL(
                    "http://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("entry");

            /** Assign textview array length by arraylist size */
            id = new TextView[nodeList.getLength()];
            published = new TextView[nodeList.getLength()];
            content = new TextView[nodeList.getLength()];
            title = new TextView[nodeList.getLength()];
            mediacontent = new TextView[nodeList.getLength()];
            mediathumbnail = new TextView[nodeList.getLength()];

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                id[i] = new TextView(this);
                published[i] = new TextView(this);
                content[i] = new TextView(this);
                title[i] = new TextView(this);

                Element fstElmnt = (Element) node;

                NodeList idList = fstElmnt.getElementsByTagName("id");
                Element idElement = (Element) idList.item(0);
                idList = idElement.getChildNodes();
                id[i].setText("Id is = "
                        + ((Node) idList.item(0)).getNodeValue());

                NodeList publishedList = fstElmnt
                        .getElementsByTagName("published");
                Element publishedElement = (Element) publishedList.item(0);
                publishedList = publishedElement.getChildNodes();
                published[i].setText("published is = "
                        + ((Node) publishedList.item(0)).getNodeValue());

                NodeList contentList = fstElmnt.getElementsByTagName("content");
                Element contentElement = (Element) contentList.item(0);
                contentList = contentElement.getChildNodes();
                content[i].setText("content is = "
                        + ((Node) contentList.item(0)).getNodeValue());

                NodeList titleList = fstElmnt.getElementsByTagName("title");
                Element titleElement = (Element) titleList.item(0);
                titleList = titleElement.getChildNodes();
                title[i].setText("title is = "
                        + ((Node) titleList.item(0)).getNodeValue());

                NodeList nodeList1 = fstElmnt.getElementsByTagName("media:group");
                System.out.println("Size is:- " +nodeList1.getLength());

                for (int j = 0; j < nodeList1.getLength(); j++) {
                    Node node1 = nodeList1.item(j);
                    mediacontent[j] = new TextView(this);
                    mediathumbnail[j] = new TextView(this);
                    Element secondElmnt = (Element) node1;
                    NodeList mediacontentList = secondElmnt.getElementsByTagName("media:content");
                    Element mediacontentElement = (Element) mediacontentList.item(0);
                    mediacontentList = mediacontentElement.getChildNodes();
                    mediacontent[j].setText("mediacontent is = "
                            + ((Node) mediacontentList.item(0)).getNodeValue());
                    layout.addView(mediacontent[j]);
                }

                layout.addView(id[i]);
                layout.addView(published[i]);
                layout.addView(content[i]);
                layout.addView(title[i]);
            }
        } catch (Exception e) {
            System.out.println("XML Pasing Excpetion = " + e);
        }

        /** Set the layout view to display */

        mScrView1.addView(layout);
        setContentView(mScrView1);
    }
}

【问题讨论】:

  • 发布你的错误日志。
  • @Downvoter 为什么要投反对票,请给我投反对票的理由?
  • @Guykun 光标进入 catch 块,logcat 中只显示“java.lang.nullpointerexception”。
  • 在你的 catch 块中添加一个 e.printStackTrace() 来获取异常的堆栈跟踪
  • @Dipak Keshariya 人们无缘无故投反对票很开心

标签: android domparser


【解决方案1】:

试试这个:

public class DomParserSampleActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ScrollView mScrView1 = new ScrollView(this);

        /** Create a new layout to display the view */
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(1);

        /** Create a new textview array to display the results */
        TextView id[];
        TextView published[];
        TextView content[];
        TextView title[];

        TextView mediacontent[];
        TextView mediathumbnail[];

        try {
            URL url = new URL(
                    "http://gdata.youtube.com/feeds/api/users/estudiosabiertostv/uploads");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("entry");

            /** Assign textview array length by arraylist size */
            id = new TextView[nodeList.getLength()];
            published = new TextView[nodeList.getLength()];
            content = new TextView[nodeList.getLength()];
            title = new TextView[nodeList.getLength()];
            mediacontent = new TextView[nodeList.getLength()];
            mediathumbnail = new TextView[nodeList.getLength()];

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                id[i] = new TextView(this);
                published[i] = new TextView(this);
                content[i] = new TextView(this);
                title[i] = new TextView(this);

                Element fstElmnt = (Element) node;

                NodeList idList = fstElmnt.getElementsByTagName("id");
                Element idElement = (Element) idList.item(0);
                idList = idElement.getChildNodes();
                id[i].setText("Id is = "
                        + ((Node) idList.item(0)).getNodeValue());

                Log.v("TAG","id: "+idList.item(0).getNodeValue());

                NodeList publishedList = fstElmnt
                        .getElementsByTagName("published");
                Element publishedElement = (Element) publishedList.item(0);
                publishedList = publishedElement.getChildNodes();
                published[i].setText("published is = "
                        + ((Node) publishedList.item(0)).getNodeValue());

                Log.v("TAG","published: "+publishedList.item(0).getNodeValue());

                NodeList contentList = fstElmnt.getElementsByTagName("content");
                Element contentElement = (Element) contentList.item(0);
                contentList = contentElement.getChildNodes();
                content[i].setText("content is = "
                        + ((Node) contentList.item(0)).getNodeValue());

                Log.v("TAG","content: "+contentList.item(0).getNodeValue());

                NodeList titleList = fstElmnt.getElementsByTagName("title");
                Element titleElement = (Element) titleList.item(0);
                titleList = titleElement.getChildNodes();
                title[i].setText("title is = "
                        + ((Node) titleList.item(0)).getNodeValue());

                Log.v("TAG","titulo: "+titleList.item(0).getNodeValue());

                NodeList nodeList1 = fstElmnt
                        .getElementsByTagName("media:group");

                for (int j = 0; j < nodeList1.getLength(); j++) {
                    Node node1 = nodeList1.item(j);
                    mediacontent[j] = new TextView(this);
                    mediathumbnail[j] = new TextView(this);

                    Element secondElmnt = (Element) node1;

                    NodeList mediacontentList = secondElmnt
                            .getElementsByTagName("media:content");
                    Element mediacontentElement = (Element) mediacontentList
                            .item(0);
                    mediacontent[j].setText("mediacontent url is = "
                            + mediacontentElement.getAttribute("url"));

                    Log.v("TAG","MEDIACONTENT: "+mediacontentElement.getAttribute("url"));

                    NodeList mediathumbnailList = secondElmnt
                            .getElementsByTagName("media:thumbnail");
                    Element mediathumbnailElement = (Element) mediathumbnailList
                            .item(0);
                    mediathumbnail[j].setText("mediathumbnail url is = "
                            + mediathumbnailElement.getAttribute("url"));

                    Log.v("TAG","MEDIATHUMBNAIL: "+mediathumbnailElement.getAttribute("url"));

                    layout.addView(mediacontent[j]);
                    layout.addView(mediathumbnail[j]);
                }

                layout.addView(id[i]);
                layout.addView(published[i]);
                layout.addView(content[i]);
                layout.addView(title[i]);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        /** Set the layout view to display */

        mScrView1.addView(layout);
        setContentView(mScrView1);
    }
}

不要忘记在线程中这样做或失败,请使用这些行 在 onCreate() 之后

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
    StrictMode.setThreadPolicy(policy);

【讨论】:

    【解决方案2】:

    试试这个

    创建一个新类 XMLParser

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    
    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;
    
    import android.util.Log;
    
    public class XMLParser {
    
        public String getXmlFromUrl(String urll) {
            String response = "";
            try {
                URLConnection conn = null;
                InputStream inputStream = null;
                URL url = new URL(urll);
                conn = url.openConnection();
                conn.setConnectTimeout(10000);
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setRequestMethod("GET");
                httpConn.setConnectTimeout(10000);
                httpConn.connect();
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    inputStream = httpConn.getInputStream();
                }
                BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                StringWriter writer=new StringWriter();
                String line="";
                while ( null!=(line=in.readLine())){
                    writer.write(line); 
                }
                response =writer.toString(); 
                }
            catch (Exception e) {
                // TODO: handle exception
            }
            return response;
        }
    
        public Document getDomElement(String xml) {
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    
            try {
    
                DocumentBuilder db = dbf.newDocumentBuilder();
    
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);
    
            } 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) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }
    
        public final String getElementValue(Node elem) {
            Node child;
            if (elem != null) {
                if (elem.hasChildNodes()) {
                    for (child = elem.getFirstChild(); child != null; child = child
                            .getNextSibling()) {
                        if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                            return child.getNodeValue();
                        }
                    }
                }
            }
            return "";
        }
    }
    

    例如你的 xml

    <results>
       <result>
         <title>title1</title>
         <description>description1</description>
         <lien>lien1</lien>
       </result>
       <result>
         <title>title2</title>
         <description>description2</description>
         <lien>lien2</lien>
       </result>
    </results>
    

    并且,在你的活动中使用它

    final String KEY_ITEM = "result"; // parent node
    final String KEY_TITLE = "title";
    final String KEY_DESC = "description";
    final String KEY_LINK = "lien";
    
    
    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl("YourXmlURL"); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element
    
    NodeList elements = doc.getElementsByTagName(KEY_ITEM);
    List<String> title= new ArrayList<String>(); // or other type
    List<String> descp= new ArrayList<String>();
    Element e;
    
    for (int i = 0; i < elements.getLength(); i++) {
        e = (Element) elements.item(i);
        title.add(parser.getValue(e, KEY_TITLE));
        descp.add(parser.getValue(e,KEY_DESC));
    }
    

    【讨论】:

    • 但是如何使用您的代码解析我的 xml 文件的
    • 在你的活动中使用 e.getAttribute("yourAttribute") 或者添加到 XMLParser 类的 getValue() 中
    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 2013-12-24
    • 2011-12-15
    • 2013-01-31
    • 2020-01-20
    • 2012-11-02
    • 2020-05-22
    • 2012-09-11
    相关资源
    最近更新 更多