[Android entry to project combat -- 8.3] -- how to parse XML format data

Table of contents

1. Preparation

EasyWebServer

2. Pull analysis method

Three, SAX analysis method


        We can submit data to the server or obtain data, but the exchange of data is not only about the content, but also about the attributes and functions of the data. When the other party receives the data message, it can be parsed according to the same structural specification, so that Take out the part you want.

        There are two formats most commonly used when transferring data over the web: XML and JSON.

1. Preparation

        Next, we need to get a piece of data in XML format, first build a simple server, and get the XML text on the server, here we use EasyWebServer to build a small server.

EasyWebServer

        EasyWebServer is a small web server software. It can create a site on your PC very quickly without the need for huge and complicated tools such as IIS.

Download address: [EasyWebServer website server download] The latest official version of EasyWebServer website server free download in 2022- Tencent Software Center official website

After the download is complete, open the software,

Click Settings, the main directory is a shared folder, and create an HTML file in the file.

 

         Then enter your ip in the browser to see the contents of the shared folder.

        If you want to form a local area network with the mobile phone, you can open the web page on the mobile phone, and continue the following operations: open the hotspot of the mobile phone, connect the notebook to the hotspot of the mobile phone, check the IP obtained by the notebook, then start the server, and then use the mobile browser to open the obtained notebook. ip, if successful, you can see the HTML files in the shared folder.

        After the above operation is successful, create a get_data.xml file in the web page directory and add the following content:

<apps>
	<app>
		<id>1</id>
		<name>Google Maps</name>
		<version>1.0</version>
	</app>
	<app>
		<id>2</id>
		<name>Chrome</name>
		<version>2.1</version>
	</app>
	<app>
		<id>3</id>
		<name>Goole Play</name>
		<version>2.3</version>
	</app>
</apps>

    The preparatory work has been completed, and the following XML data is obtained and parsed in the Android program.

2. Pull analysis method

Next, we will continue to develop on the NetworkTest project. You can move to this article first to learn HTTP access to the network.

Modify the MainActivity code as follows:

        First change the address of the HTTP request to your ip+get_data.xml, everyone is different, pay attention to modify! Then call the parseXMLWithPull(responseData) method to parse the data returned by the server.

        The code of the parseXMLWithPull() method first obtains an XmlPullParserFactory instance and obtains the XmlPullParse object, and then calls the setInput() method of this object to set the XML data returned by the server into it, and then it can be parsed.

        Parsing process: The current parsing event can be obtained through getEventType(), and then parsed in a loop. If the current parsing event is not equal to XmlPullParser.END_DOCUMENT, it means that the parsing has not been completed, and the next event can be parsed by calling the next() method.

        In the loop, get the name of the current node through getName(). If the node name is equal to id, name or version, call the nextText() method to get the specific content.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.30.175/get_data.xml")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseXMLWithPull(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



    private void parseXMLWithPull(String xmlData) {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String nodeName = xmlPullParser.getName();
                switch (eventType) {
                    // 开始解析某个结点
                    case XmlPullParser.START_TAG: {
                        if ("id".equals(nodeName)) {
                            id = xmlPullParser.nextText();
                        } else if ("name".equals(nodeName)) {
                            name = xmlPullParser.nextText();
                        } else if ("version".equals(nodeName)) {
                            version = xmlPullParser.nextText();
                        }
                        break;
                    }
                    // 完成解析某个结点
                    case XmlPullParser.END_TAG: {
                        if ("app".equals(nodeName)) {
                            Log.d("MainActivity", "id is " + id);
                            Log.d("MainActivity", "name is " + name);
                            Log.d("MainActivity", "version is " + version);
                        }
                        break;
                    }
                    default:
                        break;
                }
                eventType = xmlPullParser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

The effect is as follows:

Check the log after clicking the button

Three, SAX analysis method

        SAX parsing usage is a bit more complex than Pull parsing, but will be clearer semantically.

Create a new ContentHandler class that inherits from DefaultHand, and rewrite five methods of the parent class, as follows:

        The startDocument() method will be called when starting XML parsing, the startElement() method will be called when starting to parse a certain node, characters() will be called when getting the content in a node, and endElement() will be called when parsing a certain node node, endDocument() will be called when the entire XML parsing is completed.

public class ContentHandler extends DefaultHandler {

    private String nodeName;

    private StringBuilder id;

    private StringBuilder name;

    private StringBuilder version;

    @Override
    public void startDocument() throws SAXException {
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // 记录当前结点名
        nodeName = localName;
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        // 根据当前的结点名判断将内容添加到哪一个StringBuilder对象中
        if ("id".equals(nodeName)) {
            id.append(ch, start, length);
        } else if ("name".equals(nodeName)) {
            name.append(ch, start, length);
        } else if ("version".equals(nodeName)) {
            version.append(ch, start, length);
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if ("app".equals(localName)) {
            Log.d("ContentHandler", "id is " + id.toString().trim());
            Log.d("ContentHandler", "name is " + name.toString().trim());
            Log.d("ContentHandler", "version is " + version.toString().trim());
            // 最后要将StringBuilder清空掉
            id.setLength(0);
            name.setLength(0);
            version.setLength(0);
        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

}

Modify the MainActivity code as follows:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ...................

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.30.175/get_data.xml")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseXMLWithSAX(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void parseXMLWithSAX(String xmlData) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader xmlReader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            // 将ContentHandler的实例设置到XMLReader中
            xmlReader.setContentHandler(handler);
            // 开始执行解析
            xmlReader.parse(new InputSource(new StringReader(xmlData)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

The effect is the same as the Pull method.

Guess you like

Origin blog.csdn.net/Tir_zhang/article/details/130462019