Android XML Parser

Source: Internet
Author: User
Tags xml parser

Recently, I encountered an XML parsing problem in the project. We used the DOM parser that comes with Android to parse XML, but found a problem with Android, that is, on SDK 2.3, strings such as <,> and cannot be parsed.

Although the data we return from the server should not contain such characters and should be escaped, sometimes, due to historical reasons, the server cannot make such correction, therefore, this problem can only be solved on the client. Next I will talk about how we solve this problem.

1. Our parsing code is:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document documnet = builder.parse(in);Element root = documnet.getDocumentElement();

The In in builder. parse (in) is an inputstream input stream. For example, there is an XML section as follows:

<? XML version = "1.0"?> <DATA> <success> 1 </success> <error> <code> </code> <message> </error> <result> 

There is a title node that contains <> in the middle, but the XML has been escaped, so it should be parsed normally, but in sdk2.3 (it should be less than 3.0 ), it specially processes these escape characters. It regards the text in the title as four text nodes and the content is:

1. Every day is the day of every month! Review

2, <

3, retrouvailles

4,> 1 hour

Therefore, this is incorrect. In fact, it should be a node with the content of [every day, every day! <Symbol uvailles> 1 character]. However, in SDK 3.0, this problem was fixed.

2. cause of the problem

Well, the above is a phenomenon. Let's talk about the causes and solutions for this phenomenon.

Looking at the android source code, we found that:

Android uses Apache harmony code for XML parsing. I think the Dalvik of Android should be Apache's harmonyxml parser.

In fact, the XML parsing of Harmony uses kxml. It seems that android is a bunch of open-source code.

Next let's take a closer look: The kxml processing process is like this. it traverses the text and triggers an event when key characters such as <,/> and & are found, if you are interested, please refer to the source code;

The source code is \ libcore \ luni \ SRC \ main \ Java \ org \ apache \ harmony \ XML \ parsers \ documentbuilderimpl. java.

Row 113: xmlpullparser parser = new kxmlparser (); row 265: else if (token = xmlpullparser. text) node. appendchild (document. createtextnode (parser. gettext (); 277 rows: else if (token = xmlpullparser. entity_ref) string entity = parser. getname (); If (entityresolver! = NULL) {// todo implement this...} string replacement = resolvestandardentity (entity); If (replacement! = NULL) {node. appendchild (document. createtextnode (replacement);} else {node. appendchild (document. createentityreference (entity ));}

As you can see above, when processing the characters with & <& gt &;, it is divided into several text nodes.

3. Solution

We already know the cause of the problem. How can we solve it?

1. judge if the child node is a text node, combine all the text strings of the node.

2. Change the above processing method. This line of code is node. appendchild. When the first child node of this node is a text node, add the current character.

The method used in the project is the first one, because the method is simple and the implementation is as follows:

/**     * This method is used to indicate the specified node's all sub nodes are text node or not.     *     * @param node The specified node.     *     * @return true if all sub nodes are text type, otherwise false.     */    public static boolean areAllSubNodesTextType(Node node)    {        if (null != node)        {            int nodeCount = node.getChildNodes().getLength();            NodeList list = node.getChildNodes();            for (int i = 0; i < nodeCount; ++i)            {                short noteType = list.item(i).getNodeType();                if (Node.TEXT_NODE != noteType)                {                    return false;                }            }        }        return true;    }    /**     * Get the node value. If the node's all sub nodes are text type, it will append     * all sub node's text as a whole text and return it.     *     * @param node The specified node.     *     * @return The value.     */    private static String getNodeValue(Node node)    {        if (null == node)        {            return "";        }        StringBuffer sb = new StringBuffer();        int nodeCount = node.getChildNodes().getLength();        NodeList list = node.getChildNodes();        for (int i = 0; i < nodeCount; ++i)        {            short noteType = list.item(i).getNodeType();            if (Node.TEXT_NODE == noteType)            {                sb.append(list.item(i).getNodeValue());            }        }        return sb.toString();    }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.