使用 xmlpullparser 解析类似 html 的文档?

发布于 2024-08-13 01:21:52 字数 812 浏览 6 评论 0原文

所以我必须解析包含嵌套标签的丑陋文件,例如

<p>blah<strong>lah</strong>blah</p>

定义了嵌套标签,但我不关心它们。但它们使 XmlPullParser 失败:

XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(some_reader);
while (parser.next() != XmlPullParser.END_DOCUMENT) {
    if (XmlPullParser.START_TAG == event) {
        String tag = parser.getName();
        if (tag != null) {
            tag = tag.toLowerCase();
        } else {
            continue;
        }
       if ("p".equals(tag)) {
           String text = parser.nextText();
           // and here we go
           // org.xmlpull.v1.XmlPullParserException: expected: /p read: strong
        }
    }
}

问题:我是否有机会不预处理文件、剥离所有不必要的标签或使用第三方库?

编辑: 更新了片段以使其真正有意义。

So I've got to parse ugly files that contain nested tags like

<p>blah<strong>lah</strong>blah</p>

The nested tags are defined and I don't care about them. But they make XmlPullParser fail:

XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(some_reader);
while (parser.next() != XmlPullParser.END_DOCUMENT) {
    if (XmlPullParser.START_TAG == event) {
        String tag = parser.getName();
        if (tag != null) {
            tag = tag.toLowerCase();
        } else {
            continue;
        }
       if ("p".equals(tag)) {
           String text = parser.nextText();
           // and here we go
           // org.xmlpull.v1.XmlPullParserException: expected: /p read: strong
        }
    }
}

Question: any chance I could get away w/o preprocessing the file stripping all the unnecessary tags or using a third-party library?

EDIT:
Updated the snippet to actually make sense.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝情姑娘 2024-08-20 01:21:52

所以我放弃了 XMLPullParser 并改用 SAXParser。此外,它的性能更好

So I've got rid of XMLPullParser and switched to SAXParser. Besides, it performs better.

夜访吸血鬼 2024-08-20 01:21:52
package com.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;

public class FeedHandler extends DefaultHandler {

    StringBuilder sb = null;
    String ret = "";
    boolean bStore = false;
    int howMany = 0;

    FeedHandler() {   }

    String getResults()
    {
        return "XML parsed data.\nThere are [" + howMany + "] status updates\n\n" + ret;
    }
    @Override
    public void startDocument() throws SAXException 
    {
        // initialize "list"
    }

    @Override
    public void endDocument() throws SAXException
    {

    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {

        try {
            if (localName.equals("status"))
            {
                this.sb = new StringBuilder("");
                bStore = true;
            }
            if (localName.equals("user")) 
            {
                bStore = false;
            }
            if (localName.equals("text")) 
            {
                this.sb = new StringBuilder("");
            }
            if (localName.equals("created_at")) 
            {
                this.sb = new StringBuilder("");
            }
        } catch (Exception e) 
        {

            Log.d("error in startElement", e.getStackTrace().toString());
        }
    }
    @Override

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException 
    {

        if (bStore) 
        {
            if (localName.equals("created_at"))
            {
                ret += "Date: " + sb.toString() + "\n"; 
                sb = new StringBuilder("");
                return;

            }

            if (localName.equals("user"))
            {
                bStore = true;
            }

            if (localName.equals("text")) 
            {

                ret += "Post: " + sb.toString() + "\n\n";
                sb = new StringBuilder("");
                return;

            }


        }
        if (localName.equals("status"))
        {
            howMany++;
            bStore = false;
        }
    }
    @Override

    public void characters(char ch[], int start, int length)
    {

        if (bStore) 
        {
            String theString = new String(ch, start, length);

            this.sb.append(theString);
        }
    }

}

这是我的 xmlActivity 类,它扩展了 Activity

            InputSource is = new InputSource(getResources().openRawResource(R.raw.my));
            System.out.println("running xml file..... ");
        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // create a parser
        SAXParser parser = factory.newSAXParser();

        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();

        // instantiate our handler
        FeedHandler fh = new FeedHandler();

        // assign our handler
        xmlreader.setContentHandler(fh);

        // perform the synchronous parse
        xmlreader.parse(is);

        // should be done... let's display our results
        tvData.setText(fh.getResults());
package com.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;

public class FeedHandler extends DefaultHandler {

    StringBuilder sb = null;
    String ret = "";
    boolean bStore = false;
    int howMany = 0;

    FeedHandler() {   }

    String getResults()
    {
        return "XML parsed data.\nThere are [" + howMany + "] status updates\n\n" + ret;
    }
    @Override
    public void startDocument() throws SAXException 
    {
        // initialize "list"
    }

    @Override
    public void endDocument() throws SAXException
    {

    }

    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {

        try {
            if (localName.equals("status"))
            {
                this.sb = new StringBuilder("");
                bStore = true;
            }
            if (localName.equals("user")) 
            {
                bStore = false;
            }
            if (localName.equals("text")) 
            {
                this.sb = new StringBuilder("");
            }
            if (localName.equals("created_at")) 
            {
                this.sb = new StringBuilder("");
            }
        } catch (Exception e) 
        {

            Log.d("error in startElement", e.getStackTrace().toString());
        }
    }
    @Override

    public void endElement(String namespaceURI, String localName, String qName) throws SAXException 
    {

        if (bStore) 
        {
            if (localName.equals("created_at"))
            {
                ret += "Date: " + sb.toString() + "\n"; 
                sb = new StringBuilder("");
                return;

            }

            if (localName.equals("user"))
            {
                bStore = true;
            }

            if (localName.equals("text")) 
            {

                ret += "Post: " + sb.toString() + "\n\n";
                sb = new StringBuilder("");
                return;

            }


        }
        if (localName.equals("status"))
        {
            howMany++;
            bStore = false;
        }
    }
    @Override

    public void characters(char ch[], int start, int length)
    {

        if (bStore) 
        {
            String theString = new String(ch, start, length);

            this.sb.append(theString);
        }
    }

}

and this my xmlActivity class that extend Activity

            InputSource is = new InputSource(getResources().openRawResource(R.raw.my));
            System.out.println("running xml file..... ");
        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // create a parser
        SAXParser parser = factory.newSAXParser();

        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();

        // instantiate our handler
        FeedHandler fh = new FeedHandler();

        // assign our handler
        xmlreader.setContentHandler(fh);

        // perform the synchronous parse
        xmlreader.parse(is);

        // should be done... let's display our results
        tvData.setText(fh.getResults());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文