且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用DOM解析器XML解析

更新时间:2023-02-26 10:32:22

  //所有静态变量
    静态最终字符串URL =htt​​p://www.google.co.in/ig/api?news&hl=en;
    // XML节点键
    静态最后弦乐KEY_ITEM =新闻; //父节点
    静态最后弦乐KEY_ID =news_entry;
    静态最后弦乐KEY_NAME =称号;
    静态最后弦乐KEY_COST =URL;
    静态最后弦乐KEY_DESC =片段;    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        ArrayList的<&HashMap的LT;字符串,字符串>>菜单项=新的ArrayList<&HashMap的LT;字符串,字符串>>();        XMLParser的解析器=新XMLParser的();
        字符串XML = parser.getXmlFromUrl(URL); //获取XML
        文档的文档= parser.getDomElement(XML); //获得DOM元素        节点列表NL = doc.getElementsByTagName(KEY_ITEM);        的for(int i = 0; I< nl.getLength();我++){           HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
            元素e =(元)nl.item(I)
             的NamedNodeMap属性= e.getAttributes();
            的System.out.println(attrlength+ attributes.getLength());
             对于(int类型的= 0; A< attributes.getLength(); A ++)
             {
                     节点theAttribute = attributes.item(一);
                     的System.out.println(theAttribute.getNodeName()+=+ theAttribute.getNodeValue());
             }             节点列表NL1 = e.getElementsByTagName(KEY_ID);
             的System.out.println(KEYID+ nl1.getLength());
             对于(INT J = 0; J< nl1.getLength(); J ++)
             {
                 元素E1 =(元)nl1.item(J);                 节点列表N = e1.getElementsByTagName(KEY_NAME);                  对于(INT K = 0; K< n.getLength(); K ++){                      元素E2 =(元)n.item(K);
                //的System.out.println(结题值+ e2.getNodeName());
                     的NamedNodeMap attributes2 = e2.getAttributes();
                    //的System.out.println(attrlength+ attributes2.getLength());
                     对于(int类型的= 0; A< attributes2.getLength(); A ++)
                     {
                             节点theAttribute = attributes2.item(一);
                             的System.out.println(theAttribute.getNodeName()+=+ theAttribute.getNodeValue());                     }
                  }                  节点列表N1 = e1.getElementsByTagName(KEY_COST);
                //的System.out.println(称号+ n.getLength());
                  对于(INT K = 0; K< n1.getLength(); K ++){                      元素E2 =(元)n1.item(K);
                //的System.out.println(节点地址值);
                     的NamedNodeMap attributes2 = e2.getAttributes();
                  //的System.out.println(attrlength+ attributes2.getLength());
                     对于(int类型的= 0; A< attributes2.getLength(); A ++)
                     {
                             节点theAttribute = attributes2.item(一);
                             的System.out.println(theAttribute.getNodeName()+=+ theAttribute.getNodeValue());                     }}                     节点列表N2 = e1.getElementsByTagName(KEY_DESC);
                    //的System.out.println(称号+ n.getLength());
                      对于(INT K = 0; K< n2.getLength(); K ++){                          元素E2 =(元)n2.item(K);
                    //的System.out.println(节点段值+ e2.getNodeName());
                         的NamedNodeMap attributes2 = e2.getAttributes();
                      //的System.out.println(attrlength+ attributes2.getLength());
                         对于(int类型的= 0; A< attributes2.getLength(); A ++)
                         {
                                 节点theAttribute = attributes2.item(一);
                                 的System.out.println(theAttribute.getNodeName()+=+ theAttribute.getNodeValue());                         }
                      }             }            menuItems.add(地图);
        }    }

I need to parse document using DOM parser in android. I was unable to print all the node values My Sample XML is:`

<xml_api_reply version="1">
<news module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<title data="Top Stories"/>
<section_type data="0"/>
<news_entry>
<title data="BSE Sensex breaches 19000, Nifty above 5800"/>
<url data="http://in.reuters.com/article/2012/10/04/sensex-above-19000-on-reform-hopes-         idINDEE89301O20121004"/>
<snippet data="| MUMBAI (Reuters) - The Nifty rose above 5800 points on Thursday,     joining the Sensex in breaching key psychological levels, after continued government reform  measures sparked hopes for continued action. Banks led gainers, with ICICI Bank (ICBK."/>
<source data="Reuters India"/>
<date data="3 hours ago"/>
<num_related data="145"/>
<cluster_url data="http://google.co.in/news/story?ncl=da6VmeBXmuquikM&hl=en"/>
</news_entry>
<news_entry>
<title data="Uncertainty over Kingfisher resuming operations tomorrow"/>
<url data="http://www.hindustantimes.com/India-news/NewDelhi/Uncertainty-over- Kingfisher-resuming-operations-tomorrow/Article1-939628.aspx"/>
<snippet data="Hopes of ailing Kingfisher Airlines resuming operations on Friday has faded with last ditch efforts by the management to persuade striking engineers and pilots to return to work failing to end the deadlock over the issue of non-payment of salaries for ..."/>
 <source data="Hindustan Times"/>
 <date data="1 hour ago"/>
 <num_related data="993"/>
 <cluster_url data="http://google.co.in/news/story?ncl=dzf460GzYKTOyxM&hl=en"/>
 </news_entry>
 </news>
 </xml_api_reply>`

and I am using following code to parse the xml

xmlactivity.java

public class AndroidXMLParsingActivity extends ListActivity {

// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
//static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title ";
static final String KEY_COST = "url ";
static final String KEY_DESC = "snippet";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayList<HashMap<String, String>> menuItems = new    ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ITEM);
    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);

        // adding each child node to HashMap key => value
        //map.put(KEY_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
        //map.put(KEY_COST,   parser.getValue(e, KEY_COST));
        //map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

        // adding HashList to ArrayList
        menuItems.add(map);
    }

    // Adding menuItems to ListView
/*  ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.list_item,
            new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                    R.id.name, R.id.desciption, R.id.cost });*/

    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.list_item,
            new String[] { KEY_NAME }, new int[] {
                    R.id.name});
    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {


        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            //String name = ((TextView)       view.findViewById(R.id.name)).getText().toString();
            //String cost = ((TextView)   view.findViewById(R.id.cost)).getText().toString();
            String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),    SingleMenuItemActivity.class);
            //in.putExtra(KEY_NAME, name);
            //in.putExtra(KEY_COST, cost);
            in.putExtra(KEY_DESC, description);
            startActivity(in);

        }
    });

and xmlParser.java

 public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
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;
}

/**
 * Getting XML DOM element
 * @param XML string
 * */
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 doc;
}

/** Getting node value
  * @param elem element
  */
 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  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {     
        NodeList n = item.getElementsByTagName(str);        
        return this.getElementValue(n.item(0));
    }

}

please help me . what is the problem and suggestion thanks in advance!!!!!!!!!

 // All static variables
    static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
    // XML node keys
    static final String KEY_ITEM = "news"; // parent node
    static final String KEY_ID = "news_entry";
    static final String KEY_NAME = "title";
    static final String KEY_COST = "url";
    static final String KEY_DESC = "snippet";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ArrayList<HashMap<String, String>> menuItems = new    ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_ITEM);

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

           HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
             NamedNodeMap attributes = e.getAttributes();
            System.out.println("attrlength"+attributes.getLength());
             for (int a = 0; a < attributes.getLength(); a++) 
             {
                     Node theAttribute = attributes.item(a);
                     System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
             }

             NodeList nl1=e.getElementsByTagName(KEY_ID);
             System.out.println("keyId"+nl1.getLength());
             for(int j=0;j<nl1.getLength();j++)
             {
                 Element e1 = (Element) nl1.item(j);

                 NodeList n = e1.getElementsByTagName(KEY_NAME);

                  for (int k = 0; k < n.getLength(); k++) {

                      Element e2 = (Element) n.item(k);
                //  System.out.println("node Title value"+e2.getNodeName());
                     NamedNodeMap attributes2 = e2.getAttributes();
                    // System.out.println("attrlength"+attributes2.getLength());
                     for (int a = 0; a < attributes2.getLength(); a++) 
                     {
                             Node theAttribute = attributes2.item(a);
                             System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                     }
                  }

                  NodeList n1 = e1.getElementsByTagName(KEY_COST);
                // System.out.println("title "+n.getLength());
                  for (int k = 0; k < n1.getLength(); k++) {

                      Element e2 = (Element) n1.item(k);
                //    System.out.println("node Url value");
                     NamedNodeMap attributes2 = e2.getAttributes();
                  //   System.out.println("attrlength"+attributes2.getLength());
                     for (int a = 0; a < attributes2.getLength(); a++) 
                     {
                             Node theAttribute = attributes2.item(a);
                             System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                     }}

                     NodeList n2 = e1.getElementsByTagName(KEY_DESC);
                    // System.out.println("title "+n.getLength());
                      for (int k = 0; k < n2.getLength(); k++) {

                          Element e2 = (Element) n2.item(k);
                    //    System.out.println("node snippet value"+e2.getNodeName());
                         NamedNodeMap attributes2 = e2.getAttributes();
                      //   System.out.println("attrlength"+attributes2.getLength());
                         for (int a = 0; a < attributes2.getLength(); a++) 
                         {
                                 Node theAttribute = attributes2.item(a);
                                 System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());

                         }
                      }  

             }



            menuItems.add(map);
        }

    }