【问题标题】:Parsing CDATA in android在android中解析CDATA
【发布时间】:2012-01-01 20:46:59
【问题描述】:

我正在解析服务器上的 XML 我读取并解析它没有任何错误但我无法看到数据。

这是我的 XML:

<BookData><book><Title><![CDATA[ABC]]></Title><AuthorFName1><![CDATA[A]]></AuthorFName1><AuthorLName1><![CDATA[B]]></AuthorLName1></book><book><Title><![CDATA[XYZ]]></Title><AuthorFName1><![CDATA[A]]></AuthorFName1><AuthorLName1><![CDATA[B]]></AuthorLName1></book>

我正在使用DocumentBuilderFactory,即使我设置了代码

dbf.setCoalescing(true);

但仍然无法正常工作,请查看 DocumentBuilderFactory 的代码

Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
try {
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    doc = db.parse(is);
} catch (ParserConfigurationException e) {
    Log.d("XML parse Error:", e.getMessage());
    return null;
} catch (SAXException e) {
    Log.d("Wrong XML File Structure", e.getMessage());
    return null;
} catch (IOException e) {
    Log.d("IOException", e.getMessage());
    return null;
}

【问题讨论】:

  • StackOverflow 上有很多类似的问题。 stackoverflow.com/search?q=parse+cdata+in+android
  • 请在此处更新您的 xml,因为此 xml 不是正确的。因此,所有未来的用户都可以从这个答案中受益。
  • 嗨,Abhishek,您是否已经找到解决此 CDATA 问题的方法,如果是,请建议我解决此问题的方法,因为我也遇到与您 CADATA 相同的问题。谢谢...

标签: android xml-parsing cdata


【解决方案1】:

这是示例 XML:

<?xml version="1.1" encoding="utf-8"?>
<sample>
    <artists>
        <artist>
            <artistname><![CDATA[+&&&Plus]]></artistname>
        </artist>
        <artist>
            <artistname>015B</artistname>           
        </artist>
    </artists>
</sample>

假设您已经将xml文件内容作为xmlString,以下方法将解析带有或不带有cdata标签的xml:

private static final String XML_TAG = "artist";
    private Object parseXML(String xmlString) throws Exception {
    try {
        Document doc = getDomElement(xmlString);
        NodeList nodes = doc.getElementsByTagName(XML_TAG);
        return retrieveData(doc,nodes);
    } catch (Exception e) {
        //Logger.logError(e);
        throw e;
    }
}

static public Document getDomElement(String xmlString) throws ParserConfigurationException, SAXException, IOException {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    doc = db.parse(is);


    return doc; 
}


private Object retrieveData(Document doc, NodeList nodes) {
    ArrayList<String> list = new ArrayList<String>();
    for(int i = 0 ; i < nodes.getLength() ; i++) {
        Element element = (Element) nodes.item(i);
        String name = getValue(element, "artistname");
        list.add(name);
    }
    return list;
}

static public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return getElementValue(n.item(0));
}

static public final String getElementValue( Node elem ) {
    try {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    if( child.getNodeType() == Node.CDATA_SECTION_NODE 
                            || child.getNodeType() == Node.TEXT_NODE )
                    {
                        return child.getNodeValue().trim();
                    }
                }
            }
        }
        return "";
    } catch (DOMException e) {
        //Logger.logError(e);
        return "";
    }
} 

【讨论】:

    【解决方案2】:

    试试这个,你只需将 InputSource 实例传递给这个方法就可以了。

    private void DOMParser(InputSource inputSource) {
    
            DocumentBuilderFactory dBuilderFactory = DocumentBuilderFactory.newInstance();
            try {
                DocumentBuilder documentBuilder = dBuilderFactory.newDocumentBuilder();
                Document dom = documentBuilder.parse(inputSource);
    
                // get the root element.....
                Element docElement = dom.getDocumentElement();
                Log.i("Root Element", docElement.getTagName());
    
                // now get the NodeList of root elements
                NodeList nodeList = docElement.getElementsByTagName("book");
                Log.i("NodeList Length", nodeList.getLength()+"");
                for (int i = 0; i < nodeList.getLength(); i++) {
    
                    Element eleBook = (Element) nodeList.item(i);
                    Log.i("Book Node", eleBook.getTagName());
    
                    NodeList titleNode = eleBook.getElementsByTagName("Title");
                    Element TitleEle = (Element) titleNode.item(0);
                    Log.i("Title", "Title - "+TitleEle.getFirstChild().getNodeValue());
    
                    NodeList AuthorFName1Node = eleBook.getElementsByTagName("AuthorFName1");
                    Element AuthorFName1Ele = (Element) AuthorFName1Node.item(0);
                    Log.i("AuthorFName1","AuthorFName1 - "+AuthorFName1Ele.getFirstChild().getNodeValue());
    
                    NodeList AuthorFName11Node = eleBook.getElementsByTagName("AuthorLName1");
                    Element AuthorFName11Ele = (Element) AuthorFName11Node.item(0);
                    Log.i("AuthorLName1","AuthorLName1 - "+AuthorFName11Ele.getFirstChild().getNodeValue());
                }
            } 
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    【讨论】:

    • 感谢您的回答,但它在服务器上的输入错误没有拼写错误。那是我的打字错误。请建议我如何解析 CDATA
    • 现在你也可以自己尝试了
    • 而且,如果您无法解析 xml,您应该提供您所面临的确切问题。
    • 没有错误但也没有数据 我想在 ListView 中显示数据 喜欢的标题将是标题,副标题将是作者的名字和姓氏 请所有这些问题都有很大帮助... .. 任何人都知道如何解析 CDATA
    • 在ListView中显示数据之前,尝试解析xml的数据。
    猜你喜欢
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多