java - DOM:如何读取子节点?

标签 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>

这里发生了什么以及如何解决这个问题?

最佳答案

希望这就是您所需要的。我已复制您的响应并创建了用于测试的文件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,我就可以打印 url、宽度和高度的值

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 "";
    }
}

关于java - DOM:如何读取子节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313638/

相关文章:

c# - 在c#中获取从base64和UTF8转换后的视频文件

java - 如何在 Spring AspectJ 中使用 "declare"指令?

java - 进度条适用于 Android API 23,但不适用于 21 或 22

sql - 使用 FOR XML PATH 从 XMLTYPE 列中选择时如何删除列名

php - 如何使用 DOMDocument 替换节点的文本

java - 未捕获的类型错误 : Cannot read property 'length' of undefined while accessing arraylist through Json Object

java - 修复 Java 中的硬编码 Windows 路径,使其在 Linux 中也能正常工作

android - onclick 监听器无法在 CollapsingToolbarLayout android 中的 ImageButton 上工作

java - 尝试将 Android 中的文件 HttpPost 发送到我的服务器

用于验证 NMTOKENS 属性列表中每个值的 XML 模式