확장성 마크업 언어(XML)는 컴퓨터에서 읽을 수 있는 형식으로 문서를 인코딩하기 위한 일련의 규칙을 모은 것입니다. XML은 인터넷에서 데이터를 공유하는 데 흔히 사용되는 형식입니다.
뉴스 사이트나 블로그와 같이 콘텐츠를 자주 업데이트하는 웹사이트에서는 종종 XML 피드를 제공하여 외부 프로그램이 콘텐츠 변경사항을 잘 파악할 수 있도록 합니다. XML 데이터 업로드 및 파싱은 네트워크에 연결된 앱의 일반적인 작업입니다. 이 주제에서는 XML 문서를 파싱하고 파싱한 데이터를 사용하는 방법을 설명합니다.
Android 앱에서 웹 기반 콘텐츠를 만드는 방법에 관한 자세한 내용은 웹 기반 콘텐츠를 참고하세요.
파서 선택
XmlPullParser
를 사용하는 것이 좋습니다. 이 파서를 사용하면 Android에서 효율적이고 유지관리하기 쉬운 방식으로 XML을 파싱할 수 있습니다. Android에는 이 인터페이스의 두 가지 구현이 있습니다.
XmlPullParserFactory.newPullParser()
를 사용하는KXmlParser
Xml.newPullParser()
를 사용하는ExpatPullParser
어느 쪽을 선택하든 괜찮습니다. 이 섹션의 예에서는 Xml.newPullParser()
와 ExpatPullParser
를 사용합니다.
피드 분석
피드를 파싱하는 첫 번째 단계는 관심 있는 필드를 결정하는 것입니다. 파서는 관심 필드에 관한 데이터를 추출하고 나머지는 무시합니다.
샘플 앱의 파싱된 피드에서 다음 발췌 부분을 참고하세요. 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()
메서드를 호출하여 앱에서 관심 있는 데이터를 추출하고 처리합니다.
// 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)
}
}
...
}
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
를 반환합니다.
@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
}
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;
}
XML 파싱
XML 피드를 파싱하는 단계는 다음과 같습니다.
- 피드 분석에 설명한 대로 앱에 포함할 태그를 식별합니다. 이 예에서는
entry
태그와 이 태그의 중첩된 태그인title
,link
,summary
의 데이터를 추출합니다. - 다음과 같은 메서드를 만듭니다.
readEntry()
및readTitle()
과 같은 포함하려는 각 태그의 'read' 메서드. 파서는 입력 스트림에서 태그를 읽습니다. 이름이 지정된 태그(이 예에서는entry
,title
,link
또는summary
)를 만나면 해당 태그에 적절한 메서드를 호출합니다. 위에서 언급한 태그가 아니면 태그를 건너뜁니다.- 서로 다른 태그의 데이터를 추출하고 파서를 다음 태그로 진행하게 하는 메서드. 이 예에서 관련 메서드는 다음과 같습니다.
title
및summary
태그의 경우 파서에서readText()
를 호출합니다. 이 메서드는parser.getText()
를 호출하여 이러한 태그의 데이터를 추출합니다.link
태그의 경우 파서는 먼저 링크가 관심 있는 종류의 링크인지 확인하여 링크의 데이터를 추출합니다. 그런 다음,parser.getAttributeValue()
를 사용하여 링크 값을 추출합니다.entry
태그의 경우 파서에서readEntry()
를 호출합니다. 이 메서드는 항목의 중첩된 태그를 파싱하고 데이터 멤버title
,link
,summary
와 함께Entry
객체를 반환합니다.
- 반복적인
skip()
도우미 메서드. 이 항목에 관한 자세한 내용은 관심 없는 태그 건너뛰기를 참고하세요.
이 스니펫은 파서가 항목, 제목, 링크, 요약을 파싱하는 방법을 보여줍니다.
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
}
...
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()
메서드는 다음과 같습니다.
@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++
}
}
}
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
를 포함한 모든 이벤트를 사용합니다.- 중첩 깊이를 추적하여 원래
START_TAG
이후에 만나는 첫 번째 태그가 아니라 올바른END_TAG
에서 멈추도록 합니다.
따라서, 현재 요소에 중첩된 요소가 있으면 depth
값은 파서가 원래 START_TAG
및 이 태그에 일치하는 END_TAG
사이의 모든 이벤트를 사용할 때까지 0이 되지 않습니다. 예를 들어, 파서가 <author>
요소(두 개의 중첩된 요소인 <name>
및 <uri>
포함)를 건너뛰는 방법을 생각해보세요.
- 첫 번째로
while
루프를 통과할 때 파서가<author>
이후 만나는 태그는<name>
의START_TAG
입니다.depth
값은 2로 증가합니다. - 두 번째로
while
루프를 통과할 때 파서가 만나는 태그는END_TAG
</name>
입니다.depth
값은 1로 감소합니다. - 세 번째로
while
루프를 통과할 때 파서가 만나는 태그는START_TAG
<uri>
입니다.depth
값은 2로 증가합니다. - 네 번째로
while
루프를 통과할 때 파서가 만나는 태그는END_TAG
</uri>
입니다.depth
값은 1로 감소합니다. - 다섯 번째로(마지막으로)
while
루프를 통과할 때 파서가 만나는 태그는END_TAG
</author>
입니다.depth
값은 0으로 감소하여<author>
요소를 성공적으로 건너뛰었음을 나타냅니다.
XML 데이터 사용
예로 든 애플리케이션은 XML 피드를 비동기식으로 가져와 파싱합니다. 이 작업은 기본 UI 스레드 밖에서 처리됩니다. 처리가 완료되면 앱이 기본 활동(NetworkActivity
)에서 UI를 업데이트합니다.
다음 발췌 부분에서 loadPage()
메서드는 다음을 실행합니다.
- XML 피드의 URL을 포함한 문자열 변수를 초기화합니다.
- 사용자의 설정과 네트워크 연결에서 허용하는 경우
downloadXml(url)
메서드를 호출합니다. 이 메서드는 피드를 다운로드하여 파싱하고 UI에 표시될 문자열 결과를 반환합니다.
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.
}
}
...
}
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)
- Kotlin 코루틴을 사용하여 IO 스레드에서loadXmlFromNetwork()
메서드를 실행합니다. 피드 URL을 매개변수로 전달합니다.loadXmlFromNetwork()
메서드가 피드를 가져와서 처리합니다. 작업이 완료되면 결과 문자열을 다시 전달합니다.withContext(Dispatchers.Main)
- Kotlin 코루틴을 사용하여 기본 스레드로 돌아가고 반환된 문자열을 사용하여 UI에 표시합니다.
Java 프로그래밍 언어에서 이 프로세스는 다음과 같습니다.
Executor
가 백그라운드 스레드에서loadXmlFromNetwork()
메서드를 실행합니다. 피드 URL을 매개변수로 전달합니다.loadXmlFromNetwork()
메서드가 피드를 가져와서 처리합니다. 작업이 완료되면 결과 문자열을 다시 전달합니다.Handler
가post
를 호출하여 기본 스레드로 돌아가고 반환된 문자열을 사용하여 UI에 표시합니다.
// 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)
}
}
}
}
// 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()
메서드는 다음 스니펫에 나와 있습니다. 이 메서드는 다음을 실행합니다.
StackOverflowXmlParser
를 인스턴스화합니다. 또한,Entry
객체의List
(entries
),title
,url
,summary
에 관한 변수를 만들어 XML 피드에서 추출한 이러한 필드의 값을 보관합니다.downloadUrl()
을 호출하여 피드를 가져오고InputStream
으로 반환합니다.StackOverflowXmlParser
를 사용하여InputStream
을 파싱합니다.StackOverflowXmlParser
는 피드에서 가져온 데이터로entries
의List
를 채웁니다.entries
List
를 처리하고 피드 데이터와 HTML 마크업을 결합합니다.- 기본 활동 UI에 표시되는 HTML 문자열을 반환합니다.
// 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
}
}
// 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();
}