1

如何使用本地解析XML根据特定条件显示标签值。XML

例如,我将此XML文件存储在资产文件夹中,

<language>
<languagename>English</languagename>
<contact>EContact</contact>
<update>EUpdate</update>
</language>

<language>
<languagename>Hebrew</languagename>
<contact>HContact</contact>
<update>HUpdate</update>
</language>

我有两个按钮,当我点击 English 我想显示关于英语的数据,当我点击希伯来语时,我只想显示希伯来语。请提供帮助。

谢谢

4

1 回答 1

1

这是 XML 解析器函数,它将 XML 作为字符串。

public class XMLParser {
    public static void parser(String s) {
        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            MyXMLhandler h = new MyXMLhandler();
            xr.setContentHandler(h);
        //  Log.e("string", s);
            xr.parse(new InputSource(new StringReader(s)));

        } catch (ParserConfigurationException e) {
            Log.e("ParserError", e.getMessage());
        } catch (SAXException e) {
            Log.e("SAXError", e.getMessage());
        } catch (IOException e) {
            Log.e("IOError", e.getMessage());
        }

    }
}

使用这个处理程序类来提取你需要的信息:

public class MyXMLhandler extends DefaultHandler {
private boolean language = false;
private boolean languagename = false;
private boolean contact = false;
private boolean update = false;


@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    if (localName.equalsIgnoreCase("language")) {
        language = true;
    } else if (localName.equalsIgnoreCase("languagename")) {
        languagename = true;
    } else if (localName.equalsIgnoreCase("contact")) {
        contact = true;
    } else if (localName.equalsIgnoreCase("update")) {
        update = true;
    }
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    if (localName.equalsIgnoreCase("language")) {
        language = false;
    } else if (localName.equalsIgnoreCase("languagename")) {
        languagename = false;
    } else if (localName.equalsIgnoreCase("contact")) {
        contact = false;
    } else if (localName.equalsIgnoreCase("update")) {
        update = false;
    }
}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {

    if (language == true) {
        String s = new String(ch, start, length);

        Log.w("Language", s);

    }
    if (languagename == true) {
        String s = new String(ch, start, length);

        Log.w("Languagename", s);

    }
    if (contact == true) {
        String s = new String(ch, start, length);

        Log.w("contact", s);

    }
    if (update == true) {
        String s = new String(ch, start, length);

        Log.w("update", s);

    }

}

}

使用上面的这个函数并修改它来解决你的问题

于 2012-10-23T07:34:37.067 回答