Java Code Examples for android.util.Xml#newSerializer()

The following examples show how to use android.util.Xml#newSerializer() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AlbumImpl.java    From screenshot-tests-for-android with Apache License 2.0 6 votes vote down vote up
private void initXml() {
  if (mOutputStream != null) {
    return;
  }

  try {
    mOutputStream =
        new BufferedOutputStream(new FileOutputStream(getMetadataFile()), BUFFER_SIZE);
    mXmlSerializer = Xml.newSerializer();
    mXmlSerializer.setOutput(mOutputStream, "utf-8");
    mXmlSerializer.startDocument("utf-8", null);
    mXmlSerializer.startTag(null, "screenshots");
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 2
Source File: DeleteNonRequiredAppsTask.java    From island with Apache License 2.0 6 votes vote down vote up
private void writeSystemApps(Set<String> packageNames, File systemAppsFile) {
    try {
        FileOutputStream stream = new FileOutputStream(systemAppsFile, false);
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(stream, "utf-8");
        serializer.startDocument(null, true);
        serializer.startTag(null, TAG_SYSTEM_APPS);
        for (String packageName : packageNames) {
            serializer.startTag(null, TAG_PACKAGE_LIST_ITEM);
            serializer.attribute(null, ATTR_VALUE, packageName);
            serializer.endTag(null, TAG_PACKAGE_LIST_ITEM);
        }
        serializer.endTag(null, TAG_SYSTEM_APPS);
        serializer.endDocument();
        stream.close();
    } catch (IOException e) {
        ProvisionLogger.loge("IOException trying to write the system apps", e);
    }
}
 
Example 3
Source File: AccessibilityNodeInfoDumper.java    From JsDroidCmd with Mozilla Public License 2.0 6 votes vote down vote up
public static void dumpWindowHierarchy(UiDevice device, OutputStream out)
			throws IOException {
		XmlSerializer serializer = Xml.newSerializer();
		serializer.setFeature(
				"http://xmlpull.org/v1/doc/features.html#indent-output", true);
		serializer.setOutput(out, "UTF-8");

		serializer.startDocument("UTF-8", true);
		serializer.startTag("", "hierarchy"); // TODO(allenhair): Should we use
												// a namespace?
		serializer.attribute("", "rotation",
				Integer.toString(device.getDisplayRotation()));

		 for (AccessibilityNodeInfo root : device.getWindowRoots()) {
			 dumpNodeRec(root, serializer, 0, device.getDisplayWidth(),
			 device.getDisplayHeight());
		 }
//		dumpNodeRec(device.getUiAutomation().getRootInActiveWindow(),
//				serializer, 0, device.getDisplayWidth(),
//				device.getDisplayHeight());

		serializer.endTag("", "hierarchy");
		serializer.endDocument();
	}
 
Example 4
Source File: JsonToXml.java    From XmlToJson with Apache License 2.0 5 votes vote down vote up
private String nodeToXML(Node node) {
    XmlSerializer serializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();
    try {
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", true);

        nodeToXml(serializer, node);

        serializer.endDocument();
        return writer.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);  // TODO: do my own
    }
}
 
Example 5
Source File: FormulaList.java    From microMathematics with GNU General Public License v3.0 5 votes vote down vote up
/**
 * XML interface: procedure writes this list into the given stream
 */
public boolean writeToStream(OutputStream stream, String name)
{
    try
    {
        final StringWriter writer = new StringWriter();
        final XmlSerializer serializer = Xml.newSerializer();
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.setOutput(writer);
        serializer.startDocument("UTF-8", true);
        serializer.setPrefix(FormulaList.XML_PROP_MMT, FormulaList.XML_MMT_SCHEMA);
        serializer.startTag(FormulaList.XML_NS, FormulaList.XML_MAIN_TAG);
        serializer.startTag(FormulaList.XML_NS, XML_LIST_TAG);
        documentSettings.writeToXml(serializer);
        final ArrayList<FormulaBase> fList = formulaListView.getFormulas(FormulaBase.class);
        for (FormulaBase f : fList)
        {
            final String term = f.getBaseType().toString().toLowerCase(Locale.ENGLISH);
            serializer.startTag(FormulaList.XML_NS, term);
            f.writeToXml(serializer, String.valueOf(f.getId()));
            serializer.endTag(FormulaList.XML_NS, term);
        }
        serializer.endTag(FormulaList.XML_NS, XML_LIST_TAG);
        serializer.endTag(FormulaList.XML_NS, FormulaList.XML_MAIN_TAG);
        serializer.endDocument();
        stream.write(writer.toString().getBytes());
        return true;
    }
    catch (Exception e)
    {
        final String error = String.format(activity.getResources().getString(R.string.error_file_write), name);
        Toast.makeText(activity, error, Toast.LENGTH_LONG).show();
    }
    return false;
}
 
Example 6
Source File: WriteXML.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
private String writeXml() {
	XmlSerializer serializer = Xml.newSerializer();
	StringWriter writer = new StringWriter();
	try {
		// Hard coded stuff
		serializer.setOutput(writer);
		serializer.startDocument("UTF-8", true);
		serializer.startTag("", "people");
		serializer.attribute("", "number", "1");
		serializer.startTag("", "person");
		serializer.attribute("", "date", "20100101");
		serializer.startTag("", "name");
		serializer.text("Jim Knopf");
		serializer.endTag("", "name");
		serializer.startTag("", "url");
		serializer.text("http://www.vogella.de");
		serializer.endTag("", "url");
		serializer.startTag("", "attribute");
		serializer.text("nice guy");
		serializer.endTag("", "attribute");
		serializer.endTag("", "person");
		serializer.endTag("", "people");
		serializer.endDocument();

	} catch (Exception e) {
		throw new RuntimeException(e);
	}
	return writer.toString();
}
 
Example 7
Source File: MainActivity.java    From Android-Basics-Codes with Artistic License 2.0 4 votes vote down vote up
public void click2(View v){
  	//����xml�ļ����ݶ���
  	XmlSerializer xs = Xml.newSerializer();
  	//���ñ���·��
  	File file = new File("sdcard/sms.xml");
  	try {
	FileOutputStream fos = new FileOutputStream(file);
	
	xs.setOutput(fos, "utf-8");
	
	xs.startDocument("utf-8", true);
	xs.startTag(null, "smss");

	for (Sms sms : smsList) {
		xs.startTag(null, "sms");
		
		xs.startTag(null, "address");
		xs.text(sms.getAddress());
		xs.endTag(null, "address");
		
		xs.startTag(null, "date");
		xs.text(sms.getDate() + "");
		xs.endTag(null, "date");
		
		xs.startTag(null, "type");
		xs.text(sms.getType() + "");
		xs.endTag(null, "type");
		
		xs.startTag(null, "body");
		xs.text(sms.getBody());
		xs.endTag(null, "body");
		
		xs.endTag(null, "sms");
	}
	
	xs.endTag(null, "smss");
	xs.endDocument();
} catch (Exception e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
  }
 
Example 8
Source File: RxDeviceTool.java    From RxTools-master with Apache License 2.0 4 votes vote down vote up
/**
 * 获取手机短信并保存到xml中
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_SMS"/>}</p>
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>}</p>
 *
 * @param context 上下文
 */
public static void getAllSMS(Context context) {
    // 1.获取短信
    // 1.1获取内容解析者
    ContentResolver resolver = context.getContentResolver();
    // 1.2获取内容提供者地址   sms,sms表的地址:null  不写
    // 1.3获取查询路径
    Uri uri = Uri.parse("content://sms");
    // 1.4.查询操作
    // projection : 查询的字段
    // selection : 查询的条件
    // selectionArgs : 查询条件的参数
    // sortOrder : 排序
    Cursor cursor = resolver.query(uri, new String[]{"address", "date", "type", "body"}, null, null, null);
    // 设置最大进度
    int count = cursor.getCount();//获取短信的个数
    // 2.备份短信
    // 2.1获取xml序列器
    XmlSerializer xmlSerializer = Xml.newSerializer();
    try {
        // 2.2设置xml文件保存的路径
        // os : 保存的位置
        // encoding : 编码格式
        xmlSerializer.setOutput(new FileOutputStream(new File("/mnt/sdcard/backupsms.xml")), "utf-8");
        // 2.3设置头信息
        // standalone : 是否独立保存
        xmlSerializer.startDocument("utf-8", true);
        // 2.4设置根标签
        xmlSerializer.startTag(null, "smss");
        // 1.5.解析cursor
        while (cursor.moveToNext()) {
            SystemClock.sleep(1000);
            // 2.5设置短信的标签
            xmlSerializer.startTag(null, "sms");
            // 2.6设置文本内容的标签
            xmlSerializer.startTag(null, "address");
            String address = cursor.getString(0);
            // 2.7设置文本内容
            xmlSerializer.text(address);
            xmlSerializer.endTag(null, "address");
            xmlSerializer.startTag(null, "date");
            String date = cursor.getString(1);
            xmlSerializer.text(date);
            xmlSerializer.endTag(null, "date");
            xmlSerializer.startTag(null, "type");
            String type = cursor.getString(2);
            xmlSerializer.text(type);
            xmlSerializer.endTag(null, "type");
            xmlSerializer.startTag(null, "body");
            String body = cursor.getString(3);
            xmlSerializer.text(body);
            xmlSerializer.endTag(null, "body");
            xmlSerializer.endTag(null, "sms");
            System.out.println("address:" + address + "   date:" + date + "  type:" + type + "  body:" + body);
        }
        xmlSerializer.endTag(null, "smss");
        xmlSerializer.endDocument();
        // 2.8将数据刷新到文件中
        xmlSerializer.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: XML_Util.java    From AndroidApp with Mozilla Public License 2.0 4 votes vote down vote up
public static String updateNodeXmlBody(Map<String, String> tags, long nodeId, String changesetId, double lat, double lon, int versionNumber) throws Exception {
    XmlSerializer xmlSerializer = Xml.newSerializer();
    StringWriter writer = new StringWriter();

    if (tags == null) return null;
    /**
     *
     <osm>
     <node  id="..." changeset="12" lat="..." lon="..." version="12">
     <tag k="note" v="Just a node"/>
     ...
     </node>
     </osm>
     */

    xmlSerializer.setOutput(writer);
    // start DOCUMENT
    xmlSerializer.startDocument("UTF-8", true);
    // open tag: <osm>
    xmlSerializer.startTag("", "osm");
    // open tag: <changeset>
    xmlSerializer.startTag("", "node");
    xmlSerializer.attribute("", "id", String.valueOf(nodeId));
    xmlSerializer.attribute("", "changeset", changesetId);
    xmlSerializer.attribute("", "lat", String.valueOf(lat));
    xmlSerializer.attribute("", "lon", String.valueOf(lon));
    xmlSerializer.attribute("", "version", String.valueOf(versionNumber));


    //create tags
    for (Map.Entry<String, String> tag : tags.entrySet()) {
        xmlSerializer.startTag("", "tag");
        xmlSerializer.attribute("", "k", tag.getKey());
        xmlSerializer.attribute("", "v", tag.getValue());
        xmlSerializer.endTag("", "tag");
    }

    // close tag: </changeset>
    xmlSerializer.endTag("", "node");
    // close tag: </osm>
    xmlSerializer.endTag("", "osm");
    // end DOCUMENT
    xmlSerializer.endDocument();

    return writer.toString();
}
 
Example 10
Source File: DashManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, null);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 11
Source File: SettingsState.java    From Study_Android_Demo with Apache License 2.0 4 votes vote down vote up
private void doWriteState() {
    boolean wroteState = false;
    final int version;
    final ArrayMap<String, Setting> settings;

    synchronized (mLock) {
        version = mVersion;
        settings = new ArrayMap<>(mSettings);
        mDirty = false;
        mWriteScheduled = false;
    }

    synchronized (mWriteLock) {
        if (DEBUG_PERSISTENCE) {
            Slog.i(LOG_TAG, "[PERSIST START]");
        }

        AtomicFile destination = new AtomicFile(mStatePersistFile);
        FileOutputStream out = null;
        try {
            out = destination.startWrite();

            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(out, StandardCharsets.UTF_8.name());
            serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output",
                    true);
            serializer.startDocument(null, true);
            serializer.startTag(null, TAG_SETTINGS);
            serializer.attribute(null, ATTR_VERSION, String.valueOf(version));

            final int settingCount = settings.size();
            for (int i = 0; i < settingCount; i++) {
                Setting setting = settings.valueAt(i);

                writeSingleSetting(mVersion, serializer, setting.getId(), setting.getName(),
                        setting.getValue(), setting.getDefaultValue(), setting.getPackageName(),
                        setting.getTag(), setting.isDefaultFromSystem());

                if (DEBUG_PERSISTENCE) {
                    Slog.i(LOG_TAG, "[PERSISTED]" + setting.getName() + "="
                            + setting.getValue());
                }
            }

            serializer.endTag(null, TAG_SETTINGS);
            serializer.endDocument();
            destination.finishWrite(out);

            wroteState = true;

            if (DEBUG_PERSISTENCE) {
                Slog.i(LOG_TAG, "[PERSIST END]");
            }
        } catch (Throwable t) {
            Slog.wtf(LOG_TAG, "Failed to write settings, restoring backup", t);
            destination.failWrite(out);
        } finally {
            IoUtils.closeQuietly(out);
        }
    }

    if (wroteState) {
        synchronized (mLock) {
            addHistoricalOperationLocked(HISTORICAL_OPERATION_PERSIST, null);
        }
    }
}
 
Example 12
Source File: DashManifestParser.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, null);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 13
Source File: GpxFiles.java    From Androzic with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Saves track to file.
 * 
 * @param file valid <code>File</code>
 * @param track <code>Track</code> object containing the list of track points to save
 * @throws IOException
 */
public static void saveTrackToFile(final File file, final Track track) throws IOException
{
	XmlSerializer serializer = Xml.newSerializer();
	serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
	BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false)));
	serializer.setOutput(writer);
	serializer.startDocument("UTF-8", null);
	serializer.setPrefix("", GPX_NAMESPACE);
	serializer.startTag(GPX_NAMESPACE, GpxParser.GPX);
	serializer.attribute("", "creator", "Androzic http://androzic.com");
	serializer.startTag(GPX_NAMESPACE, GpxParser.TRK);
	serializer.startTag(GPX_NAMESPACE, GpxParser.NAME);
	serializer.text(track.name);
	serializer.endTag(GPX_NAMESPACE, GpxParser.NAME);
	serializer.startTag(GPX_NAMESPACE, GpxParser.SRC);
	serializer.text(Androzic.getDeviceName());
	serializer.endTag(GPX_NAMESPACE, GpxParser.SRC);
	
	boolean first = true;
	serializer.startTag(GPX_NAMESPACE, GpxParser.TRKSEG);
	List<TrackPoint> trackPoints = track.getAllPoints();
	for (TrackPoint tp : trackPoints)
	{
		if (!tp.continous && !first)
		{
			serializer.endTag(GPX_NAMESPACE, GpxParser.TRKSEG);
			serializer.startTag(GPX_NAMESPACE, GpxParser.TRKSEG);
		}
		serializer.startTag(GPX_NAMESPACE, GpxParser.TRKPT);
		serializer.attribute("", GpxParser.LAT, String.valueOf(tp.latitude));
		serializer.attribute("", GpxParser.LON, String.valueOf(tp.longitude));
		serializer.startTag(GPX_NAMESPACE, GpxParser.ELE);
		serializer.text(String.valueOf(tp.elevation));
		serializer.endTag(GPX_NAMESPACE, GpxParser.ELE);
		serializer.startTag(GPX_NAMESPACE, GpxParser.TIME);
		serializer.text(GpxParser.trktime.format(new Date(tp.time)));
		serializer.endTag(GPX_NAMESPACE, GpxParser.TIME);
		serializer.endTag(GPX_NAMESPACE, GpxParser.TRKPT);
		first = false;
	}
	serializer.endTag(GPX_NAMESPACE, GpxParser.TRKSEG);
	serializer.endTag(GPX_NAMESPACE, GpxParser.TRK);
	serializer.endTag(GPX_NAMESPACE, GpxParser.GPX);
	serializer.endDocument();
	serializer.flush();
	writer.close();
}
 
Example 14
Source File: InstantAppRegistry.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void writeUninstalledInstantAppMetadata(
        @NonNull InstantAppInfo instantApp, @UserIdInt int userId) {
    File appDir = getInstantApplicationDir(instantApp.getPackageName(), userId);
    if (!appDir.exists() && !appDir.mkdirs()) {
        return;
    }

    File metadataFile = new File(appDir, INSTANT_APP_METADATA_FILE);

    AtomicFile destination = new AtomicFile(metadataFile);
    FileOutputStream out = null;
    try {
        out = destination.startWrite();

        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(out, StandardCharsets.UTF_8.name());
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

        serializer.startDocument(null, true);

        serializer.startTag(null, TAG_PACKAGE);
        serializer.attribute(null, ATTR_LABEL, instantApp.loadLabel(
                mService.mContext.getPackageManager()).toString());

        serializer.startTag(null, TAG_PERMISSIONS);
        for (String permission : instantApp.getRequestedPermissions()) {
            serializer.startTag(null, TAG_PERMISSION);
            serializer.attribute(null, ATTR_NAME, permission);
            if (ArrayUtils.contains(instantApp.getGrantedPermissions(), permission)) {
                serializer.attribute(null, ATTR_GRANTED, String.valueOf(true));
            }
            serializer.endTag(null, TAG_PERMISSION);
        }
        serializer.endTag(null, TAG_PERMISSIONS);

        serializer.endTag(null, TAG_PACKAGE);

        serializer.endDocument();
        destination.finishWrite(out);
    } catch (Throwable t) {
        Slog.wtf(LOG_TAG, "Failed to write instant state, restoring backup", t);
        destination.failWrite(out);
    } finally {
        IoUtils.closeQuietly(out);
    }
}
 
Example 15
Source File: DashManifestParser.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, C.UTF8_NAME);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 16
Source File: DashManifestParser.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
/**
 * Parses an event object.
 *
 * @param xpp The current xml parser.
 * @param scratchOutputStream A {@link ByteArrayOutputStream} that's used when parsing the object.
 * @return The serialized byte array.
 * @throws XmlPullParserException If there is any error parsing this node.
 * @throws IOException If there is any error reading from the underlying input stream.
 */
protected byte[] parseEventObject(XmlPullParser xpp, ByteArrayOutputStream scratchOutputStream)
    throws XmlPullParserException, IOException {
  scratchOutputStream.reset();
  XmlSerializer xmlSerializer = Xml.newSerializer();
  xmlSerializer.setOutput(scratchOutputStream, C.UTF8_NAME);
  // Start reading everything between <Event> and </Event>, and serialize them into an Xml
  // byte array.
  xpp.nextToken();
  while (!XmlPullParserUtil.isEndTag(xpp, "Event")) {
    switch (xpp.getEventType()) {
      case (XmlPullParser.START_DOCUMENT):
        xmlSerializer.startDocument(null, false);
        break;
      case (XmlPullParser.END_DOCUMENT):
        xmlSerializer.endDocument();
        break;
      case (XmlPullParser.START_TAG):
        xmlSerializer.startTag(xpp.getNamespace(), xpp.getName());
        for (int i = 0; i < xpp.getAttributeCount(); i++) {
          xmlSerializer.attribute(xpp.getAttributeNamespace(i), xpp.getAttributeName(i),
              xpp.getAttributeValue(i));
        }
        break;
      case (XmlPullParser.END_TAG):
        xmlSerializer.endTag(xpp.getNamespace(), xpp.getName());
        break;
      case (XmlPullParser.TEXT):
        xmlSerializer.text(xpp.getText());
        break;
      case (XmlPullParser.CDSECT):
        xmlSerializer.cdsect(xpp.getText());
        break;
      case (XmlPullParser.ENTITY_REF):
        xmlSerializer.entityRef(xpp.getText());
        break;
      case (XmlPullParser.IGNORABLE_WHITESPACE):
        xmlSerializer.ignorableWhitespace(xpp.getText());
        break;
      case (XmlPullParser.PROCESSING_INSTRUCTION):
        xmlSerializer.processingInstruction(xpp.getText());
        break;
      case (XmlPullParser.COMMENT):
        xmlSerializer.comment(xpp.getText());
        break;
      case (XmlPullParser.DOCDECL):
        xmlSerializer.docdecl(xpp.getText());
        break;
      default: // fall out
    }
    xpp.nextToken();
  }
  xmlSerializer.flush();
  return scratchOutputStream.toByteArray();
}
 
Example 17
Source File: XmlUtils.java    From ticdesign with Apache License 2.0 3 votes vote down vote up
/**
 * Flatten a List into an output stream as XML.  The list can later be
 * read back with readListXml().
 *
 * @param val The list to be flattened.
 * @param out Where to write the XML data.
 *
 * @see #writeListXml(List, String, XmlSerializer)
 * @see #writeMapXml
 * @see #writeValueXml
 * @see #readListXml
 */
public static final void writeListXml(List val, OutputStream out)
throws XmlPullParserException, java.io.IOException
{
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeListXml(val, null, serializer);
    serializer.endDocument();
}
 
Example 18
Source File: XmlUtils.java    From WeexOne with MIT License 3 votes vote down vote up
/**
 * Flatten a List into an output stream as XML.  The list can later be
 * read back with readListXml().
 *
 * @param val The list to be flattened.
 * @param out Where to write the XML data.
 *
 * @see #writeListXml(List, String, XmlSerializer)
 * @see #writeMapXml
 * @see #writeValueXml
 * @see #readListXml
 */
public static final void writeListXml(List val, OutputStream out)
    throws XmlPullParserException, java.io.IOException
{
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeListXml(val, null, serializer);
    serializer.endDocument();
}
 
Example 19
Source File: Utility.java    From azure-storage-android with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a <code>XmlSerializer</code> which outputs to the specified <code>StringWriter</code>
 * 
 * @param outWriter
 *            the <code>StringWriter</code> to output to
 * @return A <code>XmlSerializer</code> instance
 * 
 * @throws IOException
 *             if there is an error setting the output.
 * @throws IllegalStateException
 *             if there is an error setting the output.
 * @throws IllegalArgumentException
 *             if there is an error setting the output.
 */
public static XmlSerializer getXmlSerializer(StringWriter outWriter) throws IllegalArgumentException,
        IllegalStateException, IOException {
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(outWriter);

    return serializer;
}
 
Example 20
Source File: XmlUtils.java    From Android-PreferencesManager with Apache License 2.0 3 votes vote down vote up
/**
 * Flatten a List into an output stream as XML. The list can later be read
 * back with readListXml().
 *
 * @param val The list to be flattened.
 * @param out Where to write the XML data.
 * @see #writeListXml(List, String, XmlSerializer)
 * @see #writeMapXml
 * @see #writeValueXml
 * @see #readListXml
 */
public static final void writeListXml(List val, OutputStream out) throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeListXml(val, null, serializer);
    serializer.endDocument();
}