如何从android中的url解析xml?

Posted

技术标签:

【中文标题】如何从android中的url解析xml?【英文标题】:How can I parse xml from url in android? 【发布时间】:2012-08-17 10:52:38 【问题描述】:

我目前正在使用从那里下载和解析的 xml。我想直接从 url 本身做。我怎样才能做到这一点?

我在下面添加了我正在使用的 sn-p。请帮忙提供一个 sn-p 或示例。谢谢。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(this.getFilesDir(), FILE_EXTRACTED);
Document dom = builder.parse(file);
Element root = dom.getDocumentElement();
root.normalize();

【问题讨论】:

【参考方案1】:

使用下面的代码从android中的url解析xml

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

        /** 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 name[];
        TextView website[];
        TextView category[];

        try 

            URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

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

            /** Assign textview array lenght by arraylist size */
            name = new TextView[nodeList.getLength()];
            website = new TextView[nodeList.getLength()];
            category = new TextView[nodeList.getLength()];

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

                Node node = nodeList.item(i);

                name[i] = new TextView(this);
                website[i] = new TextView(this);
                category[i] = new TextView(this);

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("name");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());

                NodeList websiteList = fstElmnt.getElementsByTagName("website");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                website[i].setText("Website = " + ((Node) websiteList.item(0)).getNodeValue());

                category[i].setText("Website Category = " + websiteElement.getAttribute("category"));

                layout.addView(name[i]);
                layout.addView(website[i]);
                layout.addView(category[i]);
            
         catch (Exception e) 
            System.out.println("XML Pasing Excpetion = " + e);
        

        /** Set the layout view to display */
        setContentView(layout);

    

【讨论】:

我不知道这是否可行,因为没有使用异步任务方法【参考方案2】:

我的解决方案使用已接受答案中的代码,但我发现如果不使用 AsyncTask 将无法工作

这是我的代码,首先我检索 XML 并在使用 AsyncTask 的方法中解析它

public class RetrieveFeed extends AsyncTask 

URL url;
ArrayList<String> headlines = new ArrayList();
ArrayList<String> links = new ArrayList();
@Override
protected Object doInBackground(Object[] objects) 
    // Initializing instance variables


    try 
        url = new URL("http://feeds.bbci.co.uk/news/rss.xml?edition=uk");

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(false);
        XmlPullParser xpp = factory.newPullParser();

        // We will get the XML from an input stream
        xpp.setInput(getInputStream(url), "UTF_8");

        /* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
         * However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
         * As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
         * so we should skip the "<title>" tag which is a child of "<channel>" tag,
         * and take in consideration only "<title>" tag which is a child of "<item>"
         *
         * In order to achieve this, we will make use of a boolean variable.
         */
        boolean insideItem = false;

        // Returns the type of current event: START_TAG, END_TAG, etc..
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) 
            if (eventType == XmlPullParser.START_TAG) 

                if (xpp.getName().equalsIgnoreCase("item")) 
                    insideItem = true;
                 else if (xpp.getName().equalsIgnoreCase("title")) 
                    if (insideItem)
                        headlines.add(xpp.nextText()); //extract the headline
                 else if (xpp.getName().equalsIgnoreCase("link")) 
                    if (insideItem)
                        links.add(xpp.nextText()); //extract the link of article
                
             else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) 
                insideItem = false;
            

            eventType = xpp.next(); //move to next element
        

     catch (MalformedURLException e) 
        e.printStackTrace();
     catch (XmlPullParserException e) 
        e.printStackTrace();
     catch (IOException e) 
        e.printStackTrace();
    

return headlines;



    public InputStream getInputStream(URL url) 
        try 
            return url.openConnection().getInputStream();
         catch (IOException e) 
            return null;
        
    

public ArrayList<String> heads()

    return headlines;


然后在主要活动中:

public class MainActivity extends ListActivity 

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    ArrayList<String> headlines = new ArrayList<>();

    RetrieveFeed getXML = new RetrieveFeed();
    getXML.execute();
    headlines = getXML.heads();


    // Binding data
    ArrayAdapter adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, headlines);

    setListAdapter(adapter);



确保您在清单中拥有正确的使用权限,将其放在应用程序标签内但在任何活动标签之外

<uses-permission android:name="android.permission.INTERNET"/>

最后,在扩展 ListActivity 时,您需要确保在主布局 xml 中有一个 ListView,其 id 为:

android:id="@android:id/list"

【讨论】:

最好使用 xpp.setInput(url.openConnection().getInputStream(), "UTF_8");而不是 xpp.setInput(getInputStream(url), "UTF_8");【参考方案3】:

使用此代码。

public class XMLResourceDemo extends ListActivity 

private final static String TAG = XMLResourceDemo.class.getSimpleName();
TextView selection;
ArrayList<String> items = new ArrayList<String>();

@Override
public void onCreate(Bundle icicle) 
    super.onCreate(icicle);
    setContentView(R.layout.main);
    selection = (TextView) findViewById(R.id.selection);

    try 
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();       
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser(); 
        xpp.setInput(new InputStreamReader(
            getUrlData("url")));

        while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) 
            Log.i(TAG, "doc started");
            if (xpp.getEventType() == XmlPullParser.START_TAG) 
                if (xpp.getName().equals("entry")) 
                    items.add(xpp.getAttributeValue(0));
                
            
            xpp.next();
        
     catch (Throwable t) 
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    

    setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, items));


public InputStream getUrlData(String url) throws URISyntaxException, ClientProtocolException, IOException 

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(new URI(url));
    HttpResponse res = client.execute(method);
    return res.getEntity().getContent();

【讨论】:

我可以对上面给出的sn-p进行任何更改,以调用url进行解析.. 通过使用上面的代码,您可以从 URL 中获取 xml 文档,您可以从中解析 xml。

以上是关于如何从android中的url解析xml?的主要内容,如果未能解决你的问题,请参考以下文章

从没有 .xml 扩展名的 URL 解析 XML

如何从android中的url解析多个JSON对象和数组?我正在使用一个示例,我希望在该示例中使用它,

Android XML解析错误[重复]

如何从 Kotlin 中的服务器正确获取 XML

如何仅将一些选定的 Json 数组和 Json 对象从 Url 解析到 android 设备

如何从 android http get 访问本地端口 8080 url