एक्सएमएल डेटा को पार्स करें

एक्सटेंसिबल मार्कअप लैंग्वेज (एक्सएमएल), दस्तावेज़ों को मशीन से पढ़े जा सकने वाले फ़ॉर्मैट में एन्कोड करने के नियमों का एक सेट है. इंटरनेट पर डेटा शेयर करने के लिए, एक्सएमएल एक लोकप्रिय फ़ॉर्मैट है.

न्यूज़ साइटों या ब्लॉग जैसी वेबसाइटें, अपने कॉन्टेंट को अक्सर अपडेट करती रहती हैं. ये वेबसाइटें अक्सर एक्सएमएल फ़ीड उपलब्ध कराती हैं, ताकि बाहरी प्रोग्राम, कॉन्टेंट में होने वाले बदलावों के बारे में अप-टू-डेट रह सकें. नेटवर्क से कनेक्ट किए गए ऐप्लिकेशन के लिए, एक्सएमएल डेटा अपलोड और पार्स करना एक सामान्य टास्क है. इस विषय में, एक्सएमएल दस्तावेज़ों को पार्स करने और उनके डेटा का इस्तेमाल करने का तरीका बताया गया है.

अपने Android ऐप्लिकेशन में वेब पर आधारित कॉन्टेंट बनाने के बारे में ज़्यादा जानने के लिए, वेब पर आधारित कॉन्टेंट देखें.

कोई पार्सर चुनें

हम XmlPullParser का सुझाव देते हैं. यह Android पर एक्सएमएल को पार्स करने का एक असरदार और आसान तरीका है. Android में इस इंटरफ़ेस को दो तरह से लागू किया जाता है:

दोनों में से कोई भी विकल्प चुना जा सकता है. इस सेक्शन में दिए गए उदाहरण में, ExpatPullParser और Xml.newPullParser() का इस्तेमाल किया गया है.

फ़ीड का विश्लेषण करना

किसी फ़ीड को पार्स करने का पहला चरण यह तय करना है कि आपको किन फ़ील्ड में दिलचस्पी है. पार्सर, उन फ़ील्ड का डेटा निकालता है और बाकी को अनदेखा कर देता है.

सैंपल के तौर पर मिले ऐप्लिकेशन में, पार्स किए गए फ़ीड का यह अंश देखें. StackOverflow.com पर की गई हर पोस्ट, फ़ीड में entry टैग के तौर पर दिखती है. इसमें कई नेस्ट किए गए टैग शामिल होते हैं:

<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" ...">
<title type="text">newest questions tagged android - Stack Overflow</title>
...
    <entry>
    ...
    </entry>
    <entry>
        <id>http://stackoverflow.com/q/9439999</id>
        <re:rank scheme="http://stackoverflow.com">0</re:rank>
        <title type="text">Where is my data file?</title>
        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="android"/>
        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="file"/>
        <author>
            <name>cliff2310</name>
            <uri>http://stackoverflow.com/users/1128925</uri>
        </author>
        <link rel="alternate" href="http://stackoverflow.com/questions/9439999/where-is-my-data-file" />
        <published>2012-02-25T00:30:54Z</published>
        <updated>2012-02-25T00:30:54Z</updated>
        <summary type="html">
            <p>I have an Application that requires a data file...</p>

        </summary>
    </entry>
    <entry>
    ...
    </entry>
...
</feed>

सैंपल के तौर पर मिला ऐप्लिकेशन, entry टैग और उसके नेस्ट किए गए टैग title, link, और summary के लिए डेटा इकट्ठा करता है.

पार्सर को इंस्टैंशिएट करना

फ़ीड को पार्स करने का अगला चरण, पार्सर को इंस्टैंशिएट करना और पार्स करने की प्रोसेस शुरू करना है. यह स्निपेट, पार्सर को शुरू करता है, ताकि नेमस्पेस को प्रोसेस न किया जाए और इनपुट के तौर पर दिए गए InputStream का इस्तेमाल किया जाए. यह nextTag() को कॉल करके पार्स करने की प्रोसेस शुरू करता है और readFeed() तरीके को शुरू करता है. यह तरीका, उस डेटा को निकालता है और प्रोसेस करता है जिसमें ऐप्लिकेशन की दिलचस्पी है:

Kotlin

// We don't use namespaces.
private val ns: String? = null

class StackOverflowXmlParser {

    @Throws(XmlPullParserException::class, IOException::class)
    fun parse(inputStream: InputStream): List<*> {
        inputStream.use { inputStream ->
            val parser: XmlPullParser = Xml.newPullParser()
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false)
            parser.setInput(inputStream, null)
            parser.nextTag()
            return readFeed(parser)
        }
    }
 ...
}

Java

public class StackOverflowXmlParser {
    // We don't use namespaces.
    private static final String ns = null;

    public List parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, null);
            parser.nextTag();
            return readFeed(parser);
        } finally {
            in.close();
        }
    }
 ...
}

फ़ीड पर मौजूद टेक्स्ट पढ़ें

readFeed() तरीका, फ़ीड को प्रोसेस करने का असल काम करता है. यह फ़ीड को बार-बार प्रोसेस करने के लिए, "entry" टैग वाले एलिमेंट को शुरुआती पॉइंट के तौर पर ढूंढता है. अगर कोई टैग entry टैग नहीं है, तो वह उसे छोड़ देता है. पूरी फ़ीड को बार-बार प्रोसेस करने के बाद, readFeed() एक List दिखाता है. इसमें फ़ीड से निकाली गई एंट्री (नेस्ट किए गए डेटा मेंबर के साथ) शामिल होती हैं. इसके बाद, पार्सर इस List को दिखाता है.

Kotlin

@Throws(XmlPullParserException::class, IOException::class)
private fun readFeed(parser: XmlPullParser): List<Entry> {
    val entries = mutableListOf<Entry>()

    parser.require(XmlPullParser.START_TAG, ns, "feed")
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.eventType != XmlPullParser.START_TAG) {
            continue
        }
        // Starts by looking for the entry tag.
        if (parser.name == "entry") {
            entries.add(readEntry(parser))
        } else {
            skip(parser)
        }
    }
    return entries
}

Java

private List readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    List entries = new ArrayList();

    parser.require(XmlPullParser.START_TAG, ns, "feed");
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        // Starts by looking for the entry tag.
        if (name.equals("entry")) {
            entries.add(readEntry(parser));
        } else {
            skip(parser);
        }
    }
    return entries;
}

एक्सएमएल को पार्स करना

एक्सएमएल फ़ीड को पार्स करने का तरीका यहां बताया गया है:

  1. फ़ीड का विश्लेषण करें में बताए गए तरीके से, उन टैग की पहचान करें जिन्हें आपको अपने ऐप्लिकेशन में शामिल करना है. इस उदाहरण में, entry टैग और उसके नेस्ट किए गए टैग के लिए डेटा निकाला गया है: title, link, और summary.
  2. ये तरीके बनाएं:
    • आपको जिस टैग को शामिल करना है उसके लिए "रीड" मेथड, जैसे कि readEntry() और readTitle(). पार्सर, इनपुट स्ट्रीम से टैग पढ़ता है. जब इसे इस उदाहरण में दिए गए नाम वाला कोई टैग मिलता है, जैसे कि entry, title, link या summary, तो यह उस टैग के लिए सही तरीका अपनाता है. अगर ऐसा नहीं होता है, तो यह टैग को स्किप कर देता है.
    • हर तरह के टैग के लिए डेटा निकालने और पार्सर को अगले टैग पर ले जाने के तरीके. इस उदाहरण में, काम के तरीके ये हैं:
      • title और summary टैग के लिए, पार्सर readText() को कॉल करता है. यह तरीका, parser.getText() को कॉल करके इन टैग का डेटा एक्सट्रैक्ट करता है.
      • link टैग के लिए, पार्सर लिंक का डेटा निकालता है. इसके लिए, वह पहले यह तय करता है कि लिंक उस तरह का है या नहीं जिसमें उसकी दिलचस्पी है. इसके बाद, यह लिंक की वैल्यू निकालने के लिए, parser.getAttributeValue() का इस्तेमाल करता है.
      • entry टैग के लिए, पार्सर readEntry() को कॉल करता है. यह तरीका, एंट्री के नेस्ट किए गए टैग को पार्स करता है. साथ ही, डेटा मेंबर title, link, और summary के साथ एक Entry ऑब्जेक्ट दिखाता है.
    • एक हेल्पर skip() तरीका, जो बार-बार दोहराया जाता है. इस विषय पर ज़्यादा जानकारी के लिए, उन टैग को छोड़ना जो आपके काम के नहीं हैं लेख पढ़ें.

इस स्निपेट से पता चलता है कि पार्सर, एंट्री, टाइटल, लिंक, और खास जानकारी को कैसे पार्स करता है.

Kotlin

data class Entry(val title: String?, val summary: String?, val link: String?)

// Parses the contents of an entry. If it encounters a title, summary, or link tag, hands them off
// to their respective "read" methods for processing. Otherwise, skips the tag.
@Throws(XmlPullParserException::class, IOException::class)
private fun readEntry(parser: XmlPullParser): Entry {
    parser.require(XmlPullParser.START_TAG, ns, "entry")
    var title: String? = null
    var summary: String? = null
    var link: String? = null
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.eventType != XmlPullParser.START_TAG) {
            continue
        }
        when (parser.name) {
            "title" -> title = readTitle(parser)
            "summary" -> summary = readSummary(parser)
            "link" -> link = readLink(parser)
            else -> skip(parser)
        }
    }
    return Entry(title, summary, link)
}

// Processes title tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readTitle(parser: XmlPullParser): String {
    parser.require(XmlPullParser.START_TAG, ns, "title")
    val title = readText(parser)
    parser.require(XmlPullParser.END_TAG, ns, "title")
    return title
}

// Processes link tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readLink(parser: XmlPullParser): String {
    var link = ""
    parser.require(XmlPullParser.START_TAG, ns, "link")
    val tag = parser.name
    val relType = parser.getAttributeValue(null, "rel")
    if (tag == "link") {
        if (relType == "alternate") {
            link = parser.getAttributeValue(null, "href")
            parser.nextTag()
        }
    }
    parser.require(XmlPullParser.END_TAG, ns, "link")
    return link
}

// Processes summary tags in the feed.
@Throws(IOException::class, XmlPullParserException::class)
private fun readSummary(parser: XmlPullParser): String {
    parser.require(XmlPullParser.START_TAG, ns, "summary")
    val summary = readText(parser)
    parser.require(XmlPullParser.END_TAG, ns, "summary")
    return summary
}

// For the tags title and summary, extracts their text values.
@Throws(IOException::class, XmlPullParserException::class)
private fun readText(parser: XmlPullParser): String {
    var result = ""
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.text
        parser.nextTag()
    }
    return result
}
...

Java

public static class Entry {
    public final String title;
    public final String link;
    public final String summary;

    private Entry(String title, String summary, String link) {
        this.title = title;
        this.summary = summary;
        this.link = link;
    }
}

// Parses the contents of an entry. If it encounters a title, summary, or link tag, hands them off
// to their respective "read" methods for processing. Otherwise, skips the tag.
private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
    parser.require(XmlPullParser.START_TAG, ns, "entry");
    String title = null;
    String summary = null;
    String link = null;
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        if (name.equals("title")) {
            title = readTitle(parser);
        } else if (name.equals("summary")) {
            summary = readSummary(parser);
        } else if (name.equals("link")) {
            link = readLink(parser);
        } else {
            skip(parser);
        }
    }
    return new Entry(title, summary, link);
}

// Processes title tags in the feed.
private String readTitle(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "title");
    String title = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "title");
    return title;
}

// Processes link tags in the feed.
private String readLink(XmlPullParser parser) throws IOException, XmlPullParserException {
    String link = "";
    parser.require(XmlPullParser.START_TAG, ns, "link");
    String tag = parser.getName();
    String relType = parser.getAttributeValue(null, "rel");
    if (tag.equals("link")) {
        if (relType.equals("alternate")){
            link = parser.getAttributeValue(null, "href");
            parser.nextTag();
        }
    }
    parser.require(XmlPullParser.END_TAG, ns, "link");
    return link;
}

// Processes summary tags in the feed.
private String readSummary(XmlPullParser parser) throws IOException, XmlPullParserException {
    parser.require(XmlPullParser.START_TAG, ns, "summary");
    String summary = readText(parser);
    parser.require(XmlPullParser.END_TAG, ns, "summary");
    return summary;
}

// For the tags title and summary, extracts their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
    String result = "";
    if (parser.next() == XmlPullParser.TEXT) {
        result = parser.getText();
        parser.nextTag();
    }
    return result;
}
  ...
}

उन टैग को स्किप करना जिनमें आपकी दिलचस्पी नहीं है

पार्सर को उन टैग को छोड़ना होगा जिनमें उसकी दिलचस्पी नहीं है. पार्सर का skip() तरीका यहां दिया गया है:

Kotlin

@Throws(XmlPullParserException::class, IOException::class)
private fun skip(parser: XmlPullParser) {
    if (parser.eventType != XmlPullParser.START_TAG) {
        throw IllegalStateException()
    }
    var depth = 1
    while (depth != 0) {
        when (parser.next()) {
            XmlPullParser.END_TAG -> depth--
            XmlPullParser.START_TAG -> depth++
        }
    }
}

Java

private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        throw new IllegalStateException();
    }
    int depth = 1;
    while (depth != 0) {
        switch (parser.next()) {
        case XmlPullParser.END_TAG:
            depth--;
            break;
        case XmlPullParser.START_TAG:
            depth++;
            break;
        }
    }
 }

आइए जानते हैं कि ऐसा कैसे करें:

  • अगर मौजूदा इवेंट START_TAG नहीं है, तो यह एक अपवाद दिखाता है.
  • यह START_TAG और इससे मेल खाने वाले END_TAG तक के सभी इवेंट को इस्तेमाल करता है.
  • यह नेस्टिंग की गहराई को ट्रैक करता है, ताकि यह पक्का किया जा सके कि यह सही END_TAG पर रुके, न कि ओरिजनल START_TAG के बाद मिलने वाले पहले टैग पर.

इसलिए, अगर मौजूदा एलिमेंट में नेस्ट किए गए एलिमेंट हैं, तो depth की वैल्यू तब तक 0 नहीं होगी, जब तक पार्सर ओरिजनल START_TAG और उससे मैच होने वाले END_TAG के बीच के सभी इवेंट इस्तेमाल नहीं कर लेता. उदाहरण के लिए, देखें कि पार्सर, <author> एलिमेंट को कैसे स्किप करता है. इसमें दो नेस्ट किए गए एलिमेंट, <name> और <uri> शामिल हैं:

  • while लूप के ज़रिए पहली बार, पार्सर को <author> के बाद जो अगला टैग मिलता है वह <name> के लिए START_TAG है. depth की वैल्यू बढ़कर 2 हो जाती है.
  • while लूप से दूसरी बार गुज़रने पर, पार्सर को अगला टैग END_TAG </name> मिलता है. depth की वैल्यू घटकर 1 हो जाती है.
  • while लूप के ज़रिए तीसरी बार, पार्सर को अगला टैग START_TAG <uri> मिलता है. depth की वैल्यू बढ़कर दो हो जाती है.
  • while लूप से चौथी बार गुज़रने पर, पार्सर को अगला टैग END_TAG </uri> मिलता है. depth की वैल्यू घटकर 1 हो जाती है.
  • while लूप के ज़रिए पांचवीं और आखिरी बार, पार्सर को अगला टैग END_TAG </author> मिलता है. depth की वैल्यू घटकर 0 हो जाती है. इससे पता चलता है कि <author> एलिमेंट को स्किप कर दिया गया है.

एक्सएमएल डेटा का इस्तेमाल करना

उदाहरण के तौर पर दिया गया ऐप्लिकेशन, एक्सएमएल फ़ीड को एसिंक्रोनस तरीके से फ़ेच और पार्स करता है. इससे मुख्य यूज़र इंटरफ़ेस (यूआई) थ्रेड पर प्रोसेसिंग का लोड कम हो जाता है. प्रोसेसिंग पूरी होने के बाद, ऐप्लिकेशन अपनी मुख्य गतिविधि NetworkActivity में यूआई को अपडेट करता है.

यहां दिए गए अंश में, loadPage() तरीका ये काम करता है:

  • एक्सएमएल फ़ीड के यूआरएल के साथ स्ट्रिंग वैरिएबल को शुरू करता है.
  • अगर उपयोगकर्ता की सेटिंग और इंटरनेट कनेक्शन अनुमति देता है, तो downloadXml(url) तरीके को शुरू करता है. यह तरीका, फ़ीड को डाउनलोड और पार्स करता है. साथ ही, यूज़र इंटरफ़ेस (यूआई) में दिखाने के लिए स्ट्रिंग के तौर पर नतीजा दिखाता है.

Kotlin

class NetworkActivity : Activity() {

    companion object {

        const val WIFI = "Wi-Fi"
        const val ANY = "Any"
        const val SO_URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest"
        // Whether there is a Wi-Fi connection.
        private var wifiConnected = false
        // Whether there is a mobile connection.
        private var mobileConnected = false

        // Whether the display should be refreshed.
        var refreshDisplay = true
        // The user's current network preference setting.
        var sPref: String? = null
    }
    ...
    // Asynchronously downloads the XML feed from stackoverflow.com.
    fun loadPage() {

        if (sPref.equals(ANY) && (wifiConnected || mobileConnected)) {
            downloadXml(SO_URL)
        } else if (sPref.equals(WIFI) && wifiConnected) {
            downloadXml(SO_URL)
        } else {
            // Show error.
        }
    }
    ...
}

Java

public class NetworkActivity extends Activity {
    public static final String WIFI = "Wi-Fi";
    public static final String ANY = "Any";
    private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";

    // Whether there is a Wi-Fi connection.
    private static boolean wifiConnected = false;
    // Whether there is a mobile connection.
    private static boolean mobileConnected = false;
    // Whether the display should be refreshed.
    public static boolean refreshDisplay = true;
    public static String sPref = null;
    ...
    // Asynchronously downloads the XML feed from stackoverflow.com.
    public void loadPage() {

        if((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) {
            downloadXml(URL);
        }
        else if ((sPref.equals(WIFI)) && (wifiConnected)) {
            downloadXml(URL);
        } else {
            // Show error.
        }
    }

downloadXml तरीका, Kotlin में इन तरीकों को कॉल करता है:

  • lifecycleScope.launch(Dispatchers.IO), जो IO थ्रेड पर loadXmlFromNetwork() तरीके को लॉन्च करने के लिए, Kotlin कोरूटीन का इस्तेमाल करता है. यह फ़ीड के यूआरएल को पैरामीटर के तौर पर पास करता है. loadXmlFromNetwork() तरीका, फ़ीड को फ़ेच और प्रोसेस करता है. यह प्रोसेस पूरी होने पर, नतीजे की स्ट्रिंग वापस भेजता है.
  • withContext(Dispatchers.Main), जो मुख्य थ्रेड पर वापस जाने के लिए Kotlin कोरूटीन का इस्तेमाल करता है. यह वापस मिली स्ट्रिंग को लेता है और उसे यूज़र इंटरफ़ेस (यूआई) में दिखाता है.

Java प्रोग्रामिंग लैंग्वेज में, यह प्रोसेस इस तरह होती है:

  • Executor, बैकग्राउंड थ्रेड पर loadXmlFromNetwork() तरीके को लागू करता है. यह फ़ीड के यूआरएल को पैरामीटर के तौर पर पास करता है. loadXmlFromNetwork() तरीका, फ़ीड को फ़ेच और प्रोसेस करता है. यह प्रोसेस पूरी होने पर, नतीजे की स्ट्रिंग वापस भेजता है.
  • Handler, post को कॉल करता है, ताकि मुख्य थ्रेड पर वापस जाया जा सके. इसके बाद, यह वापस मिली स्ट्रिंग को लेता है और उसे यूज़र इंटरफ़ेस (यूआई) में दिखाता है.

Kotlin

// Implementation of Kotlin coroutines used to download XML feed from stackoverflow.com.
private fun downloadXml(vararg urls: String) {
    var result: String? = null
    lifecycleScope.launch(Dispatchers.IO) {
        result = try {
            loadXmlFromNetwork(urls[0])
        } catch (e: IOException) {
            resources.getString(R.string.connection_error)
        } catch (e: XmlPullParserException) {
            resources.getString(R.string.xml_error)
        }
        withContext(Dispatchers.Main) {
            setContentView(R.layout.main)
            // Displays the HTML string in the UI via a WebView.
            findViewById<WebView>(R.id.webview)?.apply {
                loadData(result?: "", "text/html", null)
            }
        }
    }
}

Java

// Implementation of Executor and Handler used to download XML feed asynchronously from stackoverflow.com.
private void downloadXml(String... urls) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Handler handler = new Handler(Looper.getMainLooper());
    executor.execute(() -> {
        String result;
            try {
                result = loadXmlFromNetwork(urls[0]);
            } catch (IOException e) {
                result = getResources().getString(R.string.connection_error);
            } catch (XmlPullParserException e) {
                result = getResources().getString(R.string.xml_error);
            }
        String finalResult = result;
        handler.post(() -> {
            setContentView(R.layout.main);
            // Displays the HTML string in the UI via a WebView.
            WebView myWebView = (WebView) findViewById(R.id.webview);
            myWebView.loadData(finalResult, "text/html", null);
        });
    });
}

downloadXml से शुरू किया गया loadXmlFromNetwork() तरीका, अगले स्निपेट में दिखाया गया है. यह ये काम करता है:

  1. StackOverflowXmlParser को इंस्टैंशिएट करता है. यह Entry ऑब्जेक्ट (entries) के List के लिए भी वैरिएबल बनाता है. साथ ही, title, url, और summary के लिए भी वैरिएबल बनाता है, ताकि उन फ़ील्ड के लिए एक्सएमएल फ़ीड से निकाली गई वैल्यू को सेव किया जा सके.
  2. downloadUrl() को कॉल करता है, जो फ़ीड को फ़ेच करता है और उसे InputStream के तौर पर दिखाता है.
  3. InputStream को पार्स करने के लिए, StackOverflowXmlParser का इस्तेमाल करना. StackOverflowXmlParser, फ़ीड के डेटा की मदद से, entries के List में जानकारी भरता है.
  4. entries List को प्रोसेस करता है और फ़ीड डेटा को एचटीएमएल मार्कअप के साथ जोड़ता है.
  5. यह एक एचटीएमएल स्ट्रिंग दिखाता है, जो मुख्य गतिविधि के यूज़र इंटरफ़ेस (यूआई) में दिखती है.

Kotlin

// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
@Throws(XmlPullParserException::class, IOException::class)
private fun loadXmlFromNetwork(urlString: String): String {
    // Checks whether the user set the preference to include summary text.
    val pref: Boolean = PreferenceManager.getDefaultSharedPreferences(this)?.run {
        getBoolean("summaryPref", false)
    } ?: false

    val entries: List<Entry> = downloadUrl(urlString)?.use { stream ->
        // Instantiates the parser.
        StackOverflowXmlParser().parse(stream)
    } ?: emptyList()

    return StringBuilder().apply {
        append("<h3>${resources.getString(R.string.page_title)}</h3>")
        append("<em>${resources.getString(R.string.updated)} ")
        append("${formatter.format(rightNow.time)}</em>")
        // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
        // Each Entry object represents a single post in the XML feed.
        // This section processes the entries list to combine each entry with HTML markup.
        // Each entry is displayed in the UI as a link that optionally includes
        // a text summary.
        entries.forEach { entry ->
            append("<p><a href='")
            append(entry.link)
            append("'>" + entry.title + "</a></p>")
            // If the user set the preference to include summary text,
            // adds it to the display.
            if (pref) {
                append(entry.summary)
            }
        }
    }.toString()
}

// Given a string representation of a URL, sets up a connection and gets
// an input stream.
@Throws(IOException::class)
private fun downloadUrl(urlString: String): InputStream? {
    val url = URL(urlString)
    return (url.openConnection() as? HttpURLConnection)?.run {
        readTimeout = 10000
        connectTimeout = 15000
        requestMethod = "GET"
        doInput = true
        // Starts the query.
        connect()
        inputStream
    }
}

Java

// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private String loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
    InputStream stream = null;
    // Instantiates the parser.
    StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
    List<Entry> entries = null;
    String title = null;
    String url = null;
    String summary = null;
    Calendar rightNow = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat("MMM dd h:mmaa");

    // Checks whether the user set the preference to include summary text.
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean pref = sharedPrefs.getBoolean("summaryPref", false);

    StringBuilder htmlString = new StringBuilder();
    htmlString.append("<h3>" + getResources().getString(R.string.page_title) + "</h3>");
    htmlString.append("<em>" + getResources().getString(R.string.updated) + " " +
            formatter.format(rightNow.getTime()) + "</em>");

    try {
        stream = downloadUrl(urlString);
        entries = stackOverflowXmlParser.parse(stream);
    // Makes sure that the InputStream is closed after the app is
    // finished using it.
    } finally {
        if (stream != null) {
            stream.close();
        }
     }

    // StackOverflowXmlParser returns a List (called "entries") of Entry objects.
    // Each Entry object represents a single post in the XML feed.
    // This section processes the entries list to combine each entry with HTML markup.
    // Each entry is displayed in the UI as a link that optionally includes
    // a text summary.
    for (Entry entry : entries) {
        htmlString.append("<p><a href='");
        htmlString.append(entry.link);
        htmlString.append("'>" + entry.title + "</a></p>");
        // If the user set the preference to include summary text,
        // adds it to the display.
        if (pref) {
            htmlString.append(entry.summary);
        }
    }
    return htmlString.toString();
}

// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query.
    conn.connect();
    return conn.getInputStream();
}