XML Attributes parsing

118 views Asked by At

I'm building an application in which I have to parse XML attributes. My XML looks like this:

<ad type="interstitial" animation="none">
<interstitial preload="0" autoclose="0" type="url" url="http://account.mobfox.com/activation_vad.php" orientation="portrait">       
</interstitial>
</ad>

I have tried using the following code:

try {
    XMLParser parser = new XMLParser();
    xml = parser.getXmlFromUrl(URL);

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
    XmlPullParser parser1 = factory.newPullParser();
    parser1.setInput(new StringReader(xml));

    while (!"interstitial".equals(parser1.getName())
        && parser1.getEventType() != XmlPullParser.START_TAG) {
        parser1.next();
    }

    Log.d("URL --> ", parser1.getAttributeValue(null, "url"));

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

But, I'm not able to print URL from the attributes. What am I doing wrong? Any kind of help will be appreciated.

2

There are 2 answers

2
Hariharan On BEST ANSWER

Try this..

Log.d("URL --> ", ""+parser1.getAttributeValue(null, "url"));

beacuse maybe you are passing parameter in Log.d empty or null

EDIT

URL url = new URL("Your URL");
                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));

                doc.getDocumentElement().normalize();

                NodeList nodeList = doc.getElementsByTagName("ad");

                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);

                    Element fstElmnt = (Element) node;
                    NodeList nameList = fstElmnt.getElementsByTagName("interstitial");
                    Element nameElement = (Element) nameList.item(0);
                    nameList = nameElement.getChildNodes();                       

                    System.out.println("Value : "
                            + (nameElement.getAttribute("url")));
                }
0
Looking Forward On

Better you can use xpath concept. It is easy to implement. Here is the Link... Also you can run the query online here...