Android应用软件开发

194课时
2.6K学过
8分

课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
3分钟

7.3实施步骤

实施步骤

步骤1、在APP上右键选择New—Folder—Assets Floder,创建Assert文件夹,在此文件夹中新建一个XML文件students.xml,内容如下:

表7-3-1 XML文件

<Students>
<student id="1">
<name>Tom</name>
<age>25</age>
</student>
<student id="2">
<name>Peter</name>
<age>30</age>
</student>
<student id="3">
<name>Tony</name>
<age>28</age>
</student>
</Students>
3

2、在Activity文件中添加一个Textview控件,用于存放结果:

表7-3-2 activity_main.xml中的控件

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_show"/>

3、在MainActivity.Java中编写如下代码:

表7-3-3 MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class MainActivity extends Activity {
        private TextViewtv_show;
        @Override
         protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_show=(TextView)findViewById(R.id.tv_show);

        try{
InputStream is=getAssets().open("students.xml");
DocumentBuilderFactorydBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilderdBuilder=dBuilderFactory.newDocumentBuilder();
Document document=dBuilder.parse(is);
 Element element=(Element)document.getDocumentElement();
NodeListnodeList=element.getElementsByTagName("student");
        for(inti=0;i<nodeList.getLength();i++){
  Element student=(Element)nodeList.item(i);
tv_show.append(student.getAttribute("id")+"\n");
tv_show.append(student.getElementsByTagName("name").item(0).getTextContent()+"\n");
            tv_show.append(student.getElementsByTagName("age").item(0).getTextContent()+"\n");
        }

       }catch(IOException e){
e.printStackTrace();
        }catch(ParserConfigurationException e){
e.printStackTrace();
        }catch(SAXException e){
e.printStackTrace();
        }
  }
}
4