DOM:如何读取子节点?

时间:2018-03-16 05:16:46

标签: java android xml dom domparser

我正在尝试从RSS源中读取图像。我能够阅读许多图像,但我无法读取具有子属性的图像,如下所示。

<item>
      <title>TITLE HERE</title>
      <description>DESCRIPTION HERE</description>   
      <image>
         <url>http://www.wewewewe.com/CGImgs_logo/ITC.jpg</url>
         <width>80</width>
         <height>80</height>
      </image>
   </item>
   <item>

以下是我的代码

public void parse(Document dom, int startFromIndex){


        Element root = dom.getDocumentElement();
        NodeList items = root.getElementsByTagName(ITEM);


        for (int i = startFromIndex; i < items.getLength(); i++) {

            try {

                Node item = items.item(i);
                NodeList properties = item.getChildNodes();
                for (int j = 0; j < properties.getLength(); j++) {
                    Node property = properties.item(j);
                    String name = property.getNodeName();

                    if (name.equalsIgnoreCase(TITLE)) 
                    {
                        dataBean.setTitle(property.getFirstChild().getNodeValue());
                        Log.d("FeedParser", "Title: " + property.getFirstChild().getNodeValue());
                    }
                    else if (name.equalsIgnoreCase("media:content") || name.equalsIgnoreCase("image")) 
                    {

                      dataBean.setNewsImageUrl(property.getAttributes().getNamedItem("url").getNodeValue());
                      Log.d("FeedParser", "Image: " + property.getAttributes().getNamedItem("url").getNodeValue());
                    } 

                }
            }
            catch(NullPointerException nullPointer)
            {
                nullPointer.printStackTrace();
            }

        }
    }

但是,当图像在RSS中时,我可以轻松阅读内容。

<item>
      <title>TITLE HERE</title>          
      <media:content url="https://wewewe.popop90.com/images/as/as/16/world/16RIO-01/aadw-8d2a-4301-9945-02867aef3f1b-ASAS.jpg" medium="image" height="151" width="151"/>

    </item>

这里发生了什么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

希望这就是你所需要的。我已经复制了您的响应并创建了用于测试response.xml的文件,其中包含

<item>
      <title>TITLE HERE</title>
      <description>DESCRIPTION HERE</description>   
      <image>
         <url>http://www.wewewewe.com/CGImgs_logo/ITC.jpg</url>
         <width>80</width>
         <height>80</height>
      </image>
   </item>

之后使用Dom Parser我正在打印网址,宽度和高度

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.fw5.practice.R;

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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;

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

public class ParseXmlActivity extends AppCompatActivity {

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

        readXML();



    }

    private void readXML() {
        try{
            String xml = ReadFromfile("response.xml", this);
            Log.d("tag","xml = "+xml);
            Document doc = getDomElement(xml);
            NodeList nl = doc.getElementsByTagName("title");
            Log.i("tag","Response is 1 => "+getElementValue(nl.item(0)));

            NodeList n2 = doc.getElementsByTagName("description");
            if(n2.getLength()>0)
                Log.i("tag","Response is 2 => "+getElementValue(n2.item(0)));

            NodeList n3 = doc.getElementsByTagName("image");
            //You Can USe For Loop Here if you have many nodes
            /*Log.i("tag","count => "+nl.getLength());
            for (int i = 0; i < nl.getLength(); i++) {
                Element e = (Element) nl.item(i);
                Log.i("tag",i+" => "+getValue(e, "return_msg"));
            }*/
            //Log.i("tag","** "+getValue())
            if(n3.getLength()>0)
            {
                Element e = (Element) n3.item(0);
                String url = getValue(e,"url");
                String width = getValue(e,"width");
                String height = getValue(e,"height");

                Log.i("tag","Response is 3 => "+ url + "----" + width + "----" + height);
            }





        }catch (Exception ex){
            Log.e("tag",ex.getMessage());
        }
    }

    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 ReadFromfile(String fileName, Context context) {
        StringBuilder returnString = new StringBuilder();
        InputStream fIn = null;
        InputStreamReader isr = null;
        BufferedReader input = null;
        try {
            fIn = context.getResources().getAssets()
                    .open(fileName, Context.MODE_WORLD_READABLE);
            isr = new InputStreamReader(fIn);
            input = new BufferedReader(isr);
            String line = "";
            while ((line = input.readLine()) != null) {
                returnString.append(line);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                if (isr != null)
                    isr.close();
                if (fIn != null)
                    fIn.close();
                if (input != null)
                    input.close();
            } catch (Exception e2) {
                e2.getMessage();
            }
        }
        return returnString.toString();
    }

    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  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }
}