1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.internal.telephony.util; 18 19 import org.xmlpull.v1.XmlPullParser; 20 import org.xmlpull.v1.XmlPullParserException; 21 22 import java.io.IOException; 23 24 /** Utility methods for XML operations. */ 25 public final class XmlUtils { XmlUtils()26 private XmlUtils() {} 27 28 /** 29 * Moves parser to the first start tag, and expects the tag name being {@code firstElementName}. 30 */ beginDocument(XmlPullParser parser, String firstElementName)31 public static void beginDocument(XmlPullParser parser, String firstElementName) 32 throws XmlPullParserException, IOException { 33 int type; 34 while ((type = parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { 35 // no-op 36 } 37 38 if (type != parser.START_TAG) { 39 throw new XmlPullParserException("No start tag found"); 40 } 41 42 if (!parser.getName().equals(firstElementName)) { 43 throw new XmlPullParserException("Unexpected start tag: found " + parser.getName() 44 + ", expected " + firstElementName); 45 } 46 } 47 48 /** 49 * Moves parser to the next start tag. 50 */ nextElement(XmlPullParser parser)51 public static void nextElement(XmlPullParser parser) 52 throws XmlPullParserException, IOException { 53 int type; 54 while ((type = parser.next()) != parser.START_TAG && type != parser.END_DOCUMENT) { 55 // no-op 56 } 57 } 58 59 /** 60 * Moves parser to the next start tag within the {@code outerDepth}. 61 */ nextElementWithin(XmlPullParser parser, int outerDepth)62 public static boolean nextElementWithin(XmlPullParser parser, int outerDepth) 63 throws IOException, XmlPullParserException { 64 for (;;) { 65 int type = parser.next(); 66 if (type == XmlPullParser.END_DOCUMENT 67 || (type == XmlPullParser.END_TAG && parser.getDepth() == outerDepth)) { 68 return false; 69 } 70 if (type == XmlPullParser.START_TAG && parser.getDepth() == outerDepth + 1) { 71 return true; 72 } 73 } 74 } 75 } 76