怎么解析这个xml文件?

时间:2017-07-10 06:53:19

标签: android xml xml-parsing

如何在android中解析具有此结构的文件?

请帮助

  

我尝试了很多,但我无法解析Android上的这个文件

spark = SparkSession.builder \
.appName("Python Spark SQL") \    \
.config("spark.jars.packages", "graphframes:graphframes:0.5.0-spark2.1-s_2.11") \
.getOrCreate()

这是我的代码:   我的类名是XmlReader   我在onCreate()方法中使用这个类

<?xml version="1.0" encoding="utf-8" ?>
<book>
<season id="1" name="one">
    <page id="1-1" text="Page content 1" />
    <page id="1-2" text="Page content 2" />
    <page id="1-3" text="Page content 3" />
</season>
<season id="2" name="two">
    <page id="2-1" text="Page content 1" />
    <page id="2-2" text="Page content 2" />
    <page id="2-3" text="Page content 3" />
    <page id="2-4" text="Page content 4" />
    <page id="2-5" text="Page content 5" />
    <page id="2-6" text="Page content 6" />
</season>
<season id="3" name="three">
    <page id="3-1" text="Page content 1" />
    <page id="3-2" text="Page content 2" />
    <page id="3-3" text="Page content 3" />
    <page id="3-4" text="Page content 4" />
    <page id="3-5" text="Page content 5" />
    <page id="3-6" text="Page content 6" />
</season>
</book>

2 个答案:

答案 0 :(得分:0)

你可能正在寻找的是DOM解析器.DOMParser可以将XML或HTML源解析为DOM文档。

答案 1 :(得分:0)

试试这个

   try {
                InputStream mInputStream = getAssets().open("XmlData.xml");

                 XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance();
                 XmlPullParser myparser = xmlFactoryObject.newPullParser();

                myparser.setInput(mInputStream, null);


                int event = myparser.getEventType();
                while (event != XmlPullParser.END_DOCUMENT)  {
                    String name=myparser.getName();
                    switch (event){
                        case XmlPullParser.START_TAG:
                            break;

                        case XmlPullParser.END_TAG:
                            if(name.equals("page")){

                                Log.e("TAG",""+  myparser.getAttributeValue(null,"id"));
                                Log.e("Page content ",""+  myparser.getAttributeValue(null,"text"));

                            }
                            break;
                    }
                    event = myparser.next();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }