MikeB
MikeB

Reputation: 13

how to xml to string in android?

i've done this in java and it's done in almost 20 rows, but copying it in android it seems not to work. I've just to read two string from a XML file and save them in a String[]. Do i have to use "XmlPullParser" or there's a faster way?

EDIT: i'd love to try your solutions but i'm stuck with a silly problem. I've put the xml file under "res/xml_file/myFile.xml" , how do i get the path information?

Upvotes: 0

Views: 872

Answers (2)

marco
marco

Reputation: 3242

Maybe Document is the faster way. You can access your xml Element value with getTextContent() method.

This snippet assumes that Element you are looking for is a single entry

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = db.parse(inputstream);
        NodeList nodes = doc.getDocumentElement().getChildNodes();
        String value = ((Element) nodes.item(0)).getElementsByTagName("tagname").item(0).getTextContent();
    }catch (ParserConfigurationException | IOException | SAXException e){
        e.printStackTrace();
    }

Upvotes: 0

Jorge Nieto
Jorge Nieto

Reputation: 119

Android developers recommend XmlPullParser

We recommend XmlPullParser, which is an efficient and maintainable way to parse XML on Android.Historically Android has had two implementations of this interface:

  • KXmlParser via XmlPullParserFactory.newPullParser()
  • ExpatPullParser, via Xml.newPullParser()

Either choice is fine.

Here you have more info and examples: Android Developers

Personally I don't know any other way.

Upvotes: 2

Related Questions