解析xml

get_data.xml文件

<apps>
	<app>
		    <id>1</id>
			<name>aa</name>	
			<version>1.0</version>
	</app>
	
		<app>
		    <id>2</id>
			<name>bb</name>	
			<version>2.0</version>
	</app>
	
		<app>
		    <id>3</id>
			<name>cc</name>	
			<version>3.0</version>
	</app>
</apps>


1.pull 方式解析xml

/**
 * pull 解析xml
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button send = findViewById(R.id.button);
        textView = findViewById(R.id.textView);

        send.setOnClickListener(this);
    }

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

    private void sendRequestWithOkHttp()
    {
        // 开子线程
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    OkHttpClient client = new OkHttpClient();  // 创建OkHttpClient 实例

                    //post 请求 时候传递的参数
                    RequestBody requestBody = new FormBody.Builder()
                        .add("name", "xiaoming")
                        .add("pwd", "123")
                        .build();

                    Request request = new Request.Builder()    // 发送请求并获取服务器返回数据(request)
                        .url("http://xx.xx.xx.xx/get_data.xml")  // 获取要解析的xml
                        .post(requestBody)  // 不带参数默认为get请求
                        .build();

                    Response response = client.newCall(request).execute();// 返回数据的具体内容
                    String responseData = response.body().string();
                    // pull解析xml
                    parseXMLWithPull(responseData);
                }
                catch (Exception e) {

                }
            }
        }).start();
    }

    public void parseXMLWithPull(String data)
    {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(data));
            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);
                        }
                        break;
                    default:
                        break;
                }
                eventType = xmlPullParser.next(); // 解析工作未完成就一直解析
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


2.SAX解析xml

2.1 创建contentHandler 继承 DefaultHandler 实现其方法

class ContentHandler extends DefaultHandler
{
    private String nodeName;
    private StringBuilder id;
    private StringBuilder name;
    private StringBuilder version;

    // 开始解析xml时候调用
    public void startDocument()
        throws SAXException
    {
        id = new StringBuilder();
        name = new StringBuilder();
        version = new StringBuilder();
    }

    // 解析某个节点时候调用
    public void startElement(String uri, String localName,
                             String qName, Attributes attributes)
        throws SAXException
    {
        // 记录当前节点名称
        nodeName = localName;
    }

    // 获取节点内容的时候调用
    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);
        }
    }

    // 完成某个节点解析的时候调用
    public void endElement(String uri, String localName, String qName)
        throws SAXException
    {
        if("app".equals(nodeName))
        {
            // trim 去掉多余的空格等符号
            Log.d("contentHandler","id is" + id.toString().trim());
        }
        // 将StringBuilder清空 避免影响下一次的读取
        id.setLength(0);
        name.setLength(0);
        version.setLength(0);
    }

    // 完成整个xml解析的时候调用
    public void endDocument()
        throws SAXException
    {

    }
}

2.2

/**
 * SAX 解析xml
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button send = findViewById(R.id.button);
        textView = findViewById(R.id.textView);

        send.setOnClickListener(this);
    }

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

    private void sendRequestWithOkHttp()
    {
        // 开子线程
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try {
                    OkHttpClient client = new OkHttpClient();  // 创建OkHttpClient 实例

                    //post 请求 时候传递的参数
                    RequestBody requestBody = new FormBody.Builder()
                        .add("name","xiaoming")
                        .add("pwd","123")
                        .build();

                    Request request = new Request.Builder()    // 发送请求并获取服务器返回数据(request)
                        .url("http://www.baidu.com")
                        .post(requestBody)  // 不带参数默认为get请求
                        .build();

                    Response response = client.newCall(request).execute();// 返回数据的具体内容
                    String responseData = response.body().string();
                    // 解析xml
                    parseXMLWithSAX(responseData);
                    showBuffer(responseData);
                }
                catch (Exception e) {

                }
            }
        }).start();
    }

    public void parseXMLWithSAX(String data)
    {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            XMLReader reader = factory.newSAXParser().getXMLReader();
            ContentHandler handler = new ContentHandler();
            // 将 handler对象设置到reader中
            reader.setContentHandler(handler);
            // 开始执行解析
            reader.parse(new InputSource(new StringReader(data)));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showBuffer(final String response)
    {
        // ui操作  更新ui
        runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                textView.setText(response);
            }
        });
    }
}
3.DOM解析


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值