在android中解析CDATA

发布于 2024-12-17 03:09:37 字数 1255 浏览 0 评论 0原文

我正在解析服务器上的 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;
}

I'm parsing XML which is on the server I read it and parse it There is no any error But I'm unable to see the data.

Here is my 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>

I'm using DocumentBuilderFactory see the code even I set

dbf.setCoalescing(true);

But still not working please see the code for 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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷你仙 2024-12-24 03:09:37

这是示例 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 "";
    }
} 

This is the sample XML:

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

Let's say you already have the xml file content as xmlString, the following methods will parse xml with or without cdata tag:

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 "";
    }
} 
聆听风音 2024-12-24 03:09:37

尝试一下,您只需将 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();
        }
    }

Try this, you just have to pass InputSource instance to this method and it works.

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();
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文