org.xmlpull.v1.XmlSerializer#startDocument ( )源码实例Demo

下面列出了org.xmlpull.v1.XmlSerializer#startDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: android_9.0.0_r45   文件: CacheQuotaStrategy.java
@VisibleForTesting
static void saveToXml(XmlSerializer out,
        List<CacheQuotaHint> requests, long bytesWhenCalculated) throws IOException {
    out.startDocument(null, true);
    out.startTag(null, CACHE_INFO_TAG);
    int requestSize = requests.size();
    out.attribute(null, ATTR_PREVIOUS_BYTES, Long.toString(bytesWhenCalculated));

    for (int i = 0; i < requestSize; i++) {
        CacheQuotaHint request = requests.get(i);
        out.startTag(null, TAG_QUOTA);
        String uuid = request.getVolumeUuid();
        if (uuid != null) {
            out.attribute(null, ATTR_UUID, request.getVolumeUuid());
        }
        out.attribute(null, ATTR_UID, Integer.toString(request.getUid()));
        out.attribute(null, ATTR_QUOTA_IN_BYTES, Long.toString(request.getQuota()));
        out.endTag(null, TAG_QUOTA);
    }
    out.endTag(null, CACHE_INFO_TAG);
    out.endDocument();
}
 
/**
 * Generates the message request body from a string containing the message.
 * The message must be encodable as UTF-8. To be included in a web request,
 * this message request body must be written to the output stream of the web
 * request.
 * 
 * @param message
 *            A <code>String<code> containing the message to wrap in a message request body.
 * 
 * @return An array of <code>byte</code> containing the message request body
 *         encoded as UTF-8.
 * @throws IOException
 *             if there is an error writing the queue message.
 * @throws IllegalStateException
 *             if there is an error writing the queue message.
 * @throws IllegalArgumentException
 *             if there is an error writing the queue message.
 */
public static byte[] generateMessageRequestBody(final String message) throws IllegalArgumentException,
        IllegalStateException, IOException {
    final StringWriter outWriter = new StringWriter();
    final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);

    // default is UTF8
    xmlw.startDocument(Constants.UTF8_CHARSET, true);
    xmlw.startTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT);

    Utility.serializeElement(xmlw, QueueConstants.MESSAGE_TEXT_ELEMENT, message);

    // end QueueMessage_ELEMENT
    xmlw.endTag(Constants.EMPTY_STRING, QueueConstants.QUEUE_MESSAGE_ELEMENT);

    // end doc
    xmlw.endDocument();

    return outWriter.toString().getBytes(Constants.UTF8_CHARSET);
}
 
源代码3 项目: android_9.0.0_r45   文件: ShortcutService.java
@GuardedBy("mLock")
private void saveUserInternalLocked(@UserIdInt int userId, OutputStream os,
        boolean forBackup) throws IOException, XmlPullParserException {

    final BufferedOutputStream bos = new BufferedOutputStream(os);

    // Write to XML
    XmlSerializer out = new FastXmlSerializer();
    out.setOutput(bos, StandardCharsets.UTF_8.name());
    out.startDocument(null, true);

    getUserShortcutsLocked(userId).saveToXml(out, forBackup);

    out.endDocument();

    bos.flush();
    os.flush();
}
 
源代码4 项目: JsDroidCmd   文件: AccessibilityNodeInfoDumper.java
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();
	}
 
源代码5 项目: exificient   文件: SerializerExample.java
static void write(XmlSerializer xpp) throws IllegalArgumentException,
		IllegalStateException, IOException {
	xpp.startDocument(null, null);

	xpp.setPrefix("foo", "urn:foo"); // first prefix
	xpp.startTag("", "root");

	xpp.attribute("", "atRoot", "atValue");
	{
		xpp.comment("my comment");

		xpp.startTag("", "el1");
		xpp.text("el1 text");
		xpp.endTag("", "el1");
	}
	xpp.endTag("", "root");
	xpp.endDocument();
}
 
源代码6 项目: starcor.xul   文件: XulDebugMonitor.java
public synchronized boolean dumpGlobalSelector(final XulHttpServer.XulHttpServerRequest request, final XulHttpServer.XulHttpServerResponse response) {
	XmlSerializer xmlWriter = obtainXmlSerializer(response.getBodyStream());
	if (xmlWriter == null) {
		return false;
	}

	try {
		xmlWriter.startDocument("utf-8", Boolean.TRUE);
		XmlContentDumper contentDumper = initContentDumper(request.queries, xmlWriter);
		contentDumper.setNoSelectors(false);
		contentDumper.dumpSelectors(XulManager.getSelectors());
		xmlWriter.endDocument();
		xmlWriter.flush();
		return true;
	} catch (IOException e) {
		XulLog.e(TAG, e);
	}
	return false;
}
 
源代码7 项目: Cangol-appcore   文件: XmlUtils.java
/**
 * 转换Object到xml
 *
 * @param obj
 * @param useAnnotation
 * @return
 */
public static String toXml(Object obj, boolean useAnnotation) {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final XmlSerializer serializer = Xml.newSerializer();
    String result = null;
    try {
        serializer.setOutput(baos, UTF_8);
        serializer.startDocument(UTF_8, true);
        toXml(serializer, obj, useAnnotation);
        serializer.endDocument();
        baos.close();
        result = baos.toString(UTF_8);
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }
    return result;
}
 
/**
 * Writes a Block List and returns the corresponding UTF8 bytes.
 * 
 * @param blockList
 *            the Iterable of BlockEntry to write
 * @param opContext
 *            a tracking object for the request
 * @return a byte array of the UTF8 bytes representing the serialized block list.
 * @throws IOException
 *             if there is an error writing the block list.
 * @throws IllegalStateException
 *             if there is an error writing the block list.
 * @throws IllegalArgumentException
 *             if there is an error writing the block list.
 */
public static byte[] writeBlockListToStream(final Iterable<BlockEntry> blockList, final OperationContext opContext)
        throws IllegalArgumentException, IllegalStateException, IOException {

    final StringWriter outWriter = new StringWriter();
    final XmlSerializer xmlw = Utility.getXmlSerializer(outWriter);

    // default is UTF8
    xmlw.startDocument(Constants.UTF8_CHARSET, true);
    xmlw.startTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    for (final BlockEntry block : blockList) {

        if (block.getSearchMode() == BlockSearchMode.COMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.COMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.UNCOMMITTED) {
            Utility.serializeElement(xmlw, BlobConstants.UNCOMMITTED_ELEMENT, block.getId());
        }
        else if (block.getSearchMode() == BlockSearchMode.LATEST) {
            Utility.serializeElement(xmlw, BlobConstants.LATEST_ELEMENT, block.getId());
        }
    }

    // end BlockListElement
    xmlw.endTag(Constants.EMPTY_STRING, BlobConstants.BLOCK_LIST_ELEMENT);

    // end doc
    xmlw.endDocument();

    return outWriter.toString().getBytes(Constants.UTF8_CHARSET);
}
 
源代码9 项目: Study_Android_Demo   文件: SettingsStateTest.java
/** Make sure we won't pass invalid characters to XML serializer. */
public void testWriteReadNoCrash() throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();

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

    for (int ch = 0; ch < 0x10000; ch++) {
        checkWriteSingleSetting("char=0x" + Integer.toString(ch, 16), serializer,
                "key", String.valueOf((char) ch));
    }
    checkWriteSingleSetting(serializer, "k", "");
    checkWriteSingleSetting(serializer, "x", "abc");
    checkWriteSingleSetting(serializer, "abc", CRAZY_STRING);
    checkWriteSingleSetting(serializer, "def", null);

    // Invlid input, but shouoldn't crash.
    checkWriteSingleSetting(serializer, null, null);
    checkWriteSingleSetting(serializer, CRAZY_STRING, null);
    SettingsState.writeSingleSetting(
            SettingsState.SETTINGS_VERSION_NEW_ENCODING,
            serializer, null, "k", "v", null, "package", null, false);
    SettingsState.writeSingleSetting(
            SettingsState.SETTINGS_VERSION_NEW_ENCODING,
            serializer, "1", "k", "v", null, null, null, false);
}
 
private ElementSerializer startDoc(
    XmlSerializer serializer, Object element, boolean errorOnUnknown, String elementAlias)
    throws IOException {
  serializer.startDocument(null, null);
  SortedSet<String> aliases = new TreeSet<String>();
  computeAliases(element, aliases);
  if (elementAlias != null) {
    aliases.add(elementAlias);
  }
  for (String alias : aliases) {
    String uri = getNamespaceUriForAliasHandlingUnknown(errorOnUnknown, alias);
    serializer.setPrefix(alias, uri);
  }
  return new ElementSerializer(element, errorOnUnknown);
}
 
源代码11 项目: ImapNote2   文件: ConfigurationFile.java
public void SaveConfigurationToXML() throws IllegalArgumentException, IllegalStateException, IOException{
    FileOutputStream configurationFile = this.applicationContext.openFileOutput("ImapNotes2.conf", Context.MODE_PRIVATE);
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(configurationFile, "UTF-8");
    serializer.startDocument(null, Boolean.valueOf(true)); 
    serializer.startTag(null, "Configuration"); 
    serializer.startTag(null, "username");
    serializer.text(this.username);
    serializer.endTag(null, "username");
    serializer.startTag(null, "password");
    serializer.text(this.password);
    serializer.endTag(null, "password");
    serializer.startTag(null, "server");
    serializer.text(this.server);
    serializer.endTag(null, "server");
    serializer.startTag(null, "portnum");
    serializer.text(this.portnum);
    serializer.endTag(null, "portnum");
    serializer.startTag(null, "security");
    serializer.text(this.security);
    serializer.endTag(null, "security");
    serializer.startTag(null,"imapfolder");
    serializer.text(this.imapfolder);
    serializer.endTag(null, "imapfolder");
    serializer.startTag(null, "usesticky");
    serializer.text(this.usesticky);
    serializer.endTag(null, "usesticky");
    serializer.endTag(null, "Configuration"); 
    serializer.endDocument();
    serializer.flush();
    configurationFile.close();
}
 
@GuardedBy("mSessions")
private void writeSessionsLocked() {
    if (LOGD) Slog.v(TAG, "writeSessionsLocked()");

    FileOutputStream fos = null;
    try {
        fos = mSessionsFile.startWrite();

        XmlSerializer out = new FastXmlSerializer();
        out.setOutput(fos, StandardCharsets.UTF_8.name());
        out.startDocument(null, true);
        out.startTag(null, TAG_SESSIONS);
        final int size = mSessions.size();
        for (int i = 0; i < size; i++) {
            final PackageInstallerSession session = mSessions.valueAt(i);
            session.write(out, mSessionsDir);
        }
        out.endTag(null, TAG_SESSIONS);
        out.endDocument();

        mSessionsFile.finishWrite(fos);
    } catch (IOException e) {
        if (fos != null) {
            mSessionsFile.failWrite(fos);
        }
    }
}
 
/**
 * Using {@link AccessibilityNodeInfo} this method will walk the layout hierarchy and return
 * String object of xml hierarchy
 *
 * @param root The root accessibility node.
 */
public static String getWindowXMLHierarchy(AccessibilityNodeInfo root) throws UiAutomator2Exception {
    final long startTime = SystemClock.uptimeMillis();
    StringWriter xmlDump = new StringWriter();
    try {

        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(xmlDump);
        serializer.startDocument("UTF-8", true);
        serializer.startTag("", "hierarchy");

        if (root != null) {
            int width = -1;
            int height = -1;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                // getDefaultDisplay method available since API level 18
                Display display = Device.getInstance().getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                width = size.x;
                height = size.y;

                serializer.attribute("", "rotation", Integer.toString(display.getRotation()));
            }

            dumpNodeRec(root, serializer, 0, width, height);
        }

        serializer.endTag("", "hierarchy");
        serializer.endDocument();

        /*FileWriter writer = new FileWriter(dumpFile);
        writer.write(stringWriter.toString());
        writer.close();*/
    } catch (IOException e) {
        Log.e("failed to dump window to file", e);
    }
    final long endTime = SystemClock.uptimeMillis();
    Log.i("Fetch time: " + (endTime - startTime) + "ms");
    return xmlDump.toString();
}
 
源代码14 项目: Telegram   文件: DashManifestParser.java
/**
 * 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();
}
 
源代码15 项目: android_9.0.0_r45   文件: AppWarnings.java
/**
 * Writes the configuration file.
 * <p>
 * <strong>Note:</strong> Should be called from the ActivityManagerService thread unless you
 * don't care where you're doing I/O operations. But you <i>do</i> care, don't you?
 */
private void writeConfigToFileAmsThread() {
    // Create a shallow copy so that we don't have to synchronize on config.
    final HashMap<String, Integer> packageFlags;
    synchronized (mPackageFlags) {
        packageFlags = new HashMap<>(mPackageFlags);
    }

    FileOutputStream fos = null;
    try {
        fos = mConfigFile.startWrite();

        final XmlSerializer out = new FastXmlSerializer();
        out.setOutput(fos, StandardCharsets.UTF_8.name());
        out.startDocument(null, true);
        out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        out.startTag(null, "packages");

        for (Map.Entry<String, Integer> entry : packageFlags.entrySet()) {
            String pkg = entry.getKey();
            int mode = entry.getValue();
            if (mode == 0) {
                continue;
            }
            out.startTag(null, "package");
            out.attribute(null, "name", pkg);
            out.attribute(null, "flags", Integer.toString(mode));
            out.endTag(null, "package");
        }

        out.endTag(null, "packages");
        out.endDocument();

        mConfigFile.finishWrite(fos);
    } catch (java.io.IOException e1) {
        Slog.w(TAG, "Error writing package metadata", e1);
        if (fos != null) {
            mConfigFile.failWrite(fos);
        }
    }
}
 
源代码16 项目: AcDisplay   文件: XmlUtils.java
/**
 * Flatten a Map into an output stream as XML.  The map can later be
 * read back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static void writeMapXml(Map val, OutputStream out)
        throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}
 
源代码17 项目: AcDisplay   文件: XmlUtils.java
/**
 * 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 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();
}
 
源代码18 项目: HtmlCompat   文件: XmlUtils.java
/**
 * 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();
}
 
源代码19 项目: Android-PreferencesManager   文件: XmlUtils.java
/**
 * Flatten a Map into an output stream as XML. The map can later be read
 * back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static final void writeMapXml(Map val, OutputStream out) throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}
 
源代码20 项目: TowerCollector   文件: XmlUtils.java
/**
 * Flatten a Map into an output stream as XML.  The map can later be
 * read back with readMapXml().
 *
 * @param val The map to be flattened.
 * @param out Where to write the XML data.
 *
 * @see #writeMapXml(Map, String, XmlSerializer)
 * @see #writeListXml
 * @see #writeValueXml
 * @see #readMapXml
 */
public static final void writeMapXml(Map val, OutputStream out)
        throws XmlPullParserException, java.io.IOException {
    XmlSerializer serializer = new FastXmlSerializer();
    serializer.setOutput(out, "utf-8");
    serializer.startDocument(null, true);
    serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
    writeMapXml(val, null, serializer);
    serializer.endDocument();
}