XmlTestUtils.java revision 2caaa7420df26fafc147757d0693d98cf0ed1607
1package com.android.settings.testutils;
2
3import android.content.res.Resources;
4import android.content.res.XmlResourceParser;
5
6import android.content.Context;
7import android.text.TextUtils;
8import android.util.AttributeSet;
9import android.util.Xml;
10import com.android.settings.search2.XmlParserUtils;
11import org.xmlpull.v1.XmlPullParser;
12import org.xmlpull.v1.XmlPullParserException;
13
14import java.util.ArrayList;
15import java.util.List;
16
17/**
18 * Util class for parsing XML
19 */
20public class XmlTestUtils {
21
22    /**
23     * Parses a preference screen's xml, collects and returns all keys used by preferences
24     * on the screen.
25     *
26     * @param context of the preference screen.
27     * @param xmlId of the Preference Xml to be parsed.
28     * @return List of all keys in the preference Xml
29     */
30    public static List<String> getKeysFromPreferenceXml(Context context, int xmlId) {
31        final XmlResourceParser parser = context.getResources().getXml(xmlId);
32        final AttributeSet attrs = Xml.asAttributeSet(parser);
33        final List<String> keys = new ArrayList<>();
34        String key;
35        try {
36            while (parser.next() != XmlPullParser.END_DOCUMENT) {
37                try {
38                    key = XmlParserUtils.getDataKey(context, attrs);
39                    if (!TextUtils.isEmpty(key)) {
40                        keys.add(key);
41                    }
42                } catch (NullPointerException e) {
43                    continue;
44                } catch (Resources.NotFoundException e) {
45                    continue;
46                }
47            }
48        } catch (java.io.IOException e) {
49            return null;
50        } catch (XmlPullParserException e) {
51            return null;
52        }
53
54        return keys;
55    }
56}