下面列出了org.xmlpull.v1.XmlSerializer#endDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
serializer.endTag("", "hierarchy");
serializer.endDocument();
}
/**
* Using {@link AccessibilityNodeInfo} this method will walk the layout hierarchy and return
* String object of xml hierarchy
*
* @param root The root accessibility node.
* @param withClassName whether the output tag name is classname,
* false, the dump will be exactly same as UiAutomator
* true, each dump node tag name is classname
*/
public static String getWindowXMLHierarchy(AccessibilityNodeInfo root, boolean withClassName)
throws RuntimeException {
StringWriter xmlDump = new StringWriter();
try {
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(xmlDump);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "hierarchy");
if (root != null) {
Point physicalSize = getDevicePhysicalSize();
dumpNodeRec(root, serializer, 0, physicalSize.x, physicalSize.y, withClassName);
}
serializer.endTag("", "hierarchy");
serializer.endDocument();
} catch (IOException e) {
Log.e(TAG, "failed to dump window to file " + e.getMessage());
}
return xmlDump.toString();
}
@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();
}
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;
}
private StringWriter saveToXml(TaskRecord task) throws IOException, XmlPullParserException {
if (DEBUG) Slog.d(TAG, "saveToXml: task=" + task);
final XmlSerializer xmlSerializer = new FastXmlSerializer();
StringWriter stringWriter = new StringWriter();
xmlSerializer.setOutput(stringWriter);
if (DEBUG) xmlSerializer.setFeature(
"http://xmlpull.org/v1/doc/features.html#indent-output", true);
// save task
xmlSerializer.startDocument(null, true);
xmlSerializer.startTag(null, TAG_TASK);
task.saveToXml(xmlSerializer);
xmlSerializer.endTag(null, TAG_TASK);
xmlSerializer.endDocument();
xmlSerializer.flush();
return stringWriter;
}
public void writeToXML(OutputStream stream) throws IOException {
XmlSerializer out = new FastXmlSerializer();
out.setOutput(stream, StandardCharsets.UTF_8.name());
out.startDocument(null, true);
out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
final LocalDate cutOffDate = mInjector.getLocalDate().minusDays(MAX_DAYS_TO_TRACK);
out.startTag(null, TAG_AMBIENT_BRIGHTNESS_STATS);
for (Map.Entry<Integer, Deque<AmbientBrightnessDayStats>> entry : mStats.entrySet()) {
for (AmbientBrightnessDayStats userDayStats : entry.getValue()) {
int userSerialNumber = mInjector.getUserSerialNumber(mUserManager,
entry.getKey());
if (userSerialNumber != -1 && userDayStats.getLocalDate().isAfter(cutOffDate)) {
out.startTag(null, TAG_AMBIENT_BRIGHTNESS_DAY_STATS);
out.attribute(null, ATTR_USER, Integer.toString(userSerialNumber));
out.attribute(null, ATTR_LOCAL_DATE,
userDayStats.getLocalDate().toString());
StringBuilder bucketBoundariesValues = new StringBuilder();
StringBuilder timeSpentValues = new StringBuilder();
for (int i = 0; i < userDayStats.getBucketBoundaries().length; i++) {
if (i > 0) {
bucketBoundariesValues.append(",");
timeSpentValues.append(",");
}
bucketBoundariesValues.append(userDayStats.getBucketBoundaries()[i]);
timeSpentValues.append(userDayStats.getStats()[i]);
}
out.attribute(null, ATTR_BUCKET_BOUNDARIES,
bucketBoundariesValues.toString());
out.attribute(null, ATTR_BUCKET_STATS, timeSpentValues.toString());
out.endTag(null, TAG_AMBIENT_BRIGHTNESS_DAY_STATS);
}
}
}
out.endTag(null, TAG_AMBIENT_BRIGHTNESS_STATS);
out.endDocument();
stream.flush();
}
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();
}
private void serialize(
XmlSerializer serializer,
String elementNamespaceUri,
String elementLocalName,
Object element,
boolean errorOnUnknown)
throws IOException {
String elementAlias = elementNamespaceUri == null ? null : getAliasForUri(elementNamespaceUri);
startDoc(serializer, element, errorOnUnknown, elementAlias)
.serialize(serializer, elementNamespaceUri, elementLocalName);
serializer.endDocument();
}
private void xmlExport(OutputStream out) throws 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);
serializer.startTag(null, "trackercontrol");
serializer.startTag(null, "application");
xmlExport(PreferenceManager.getDefaultSharedPreferences(this), serializer);
serializer.endTag(null, "application");
serializer.startTag(null, "wifi");
xmlExport(getSharedPreferences("wifi", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "wifi");
serializer.startTag(null, "mobile");
xmlExport(getSharedPreferences("other", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "mobile");
serializer.startTag(null, "screen_wifi");
xmlExport(getSharedPreferences("screen_wifi", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "screen_wifi");
serializer.startTag(null, "screen_other");
xmlExport(getSharedPreferences("screen_other", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "screen_other");
serializer.startTag(null, "roaming");
xmlExport(getSharedPreferences("roaming", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "roaming");
serializer.startTag(null, "lockdown");
xmlExport(getSharedPreferences("lockdown", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "lockdown");
serializer.startTag(null, "apply");
xmlExport(getSharedPreferences("apply", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "apply");
serializer.startTag(null, "notify");
xmlExport(getSharedPreferences("notify", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "notify");
serializer.startTag(null, "filter");
filterExport(serializer);
serializer.endTag(null, "filter");
serializer.startTag(null, "forward");
forwardExport(serializer);
serializer.endTag(null, "forward");
serializer.startTag(null, "blocklist");
xmlExport(getSharedPreferences(PREF_BLOCKLIST, Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "blocklist");
serializer.endTag(null, "trackercontrol");
serializer.endDocument();
serializer.flush();
}
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);
}
}
}
private void xmlExport(OutputStream out) throws 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);
serializer.startTag(null, "netguard");
serializer.startTag(null, "application");
xmlExport(PreferenceManager.getDefaultSharedPreferences(this), serializer);
serializer.endTag(null, "application");
serializer.startTag(null, "wifi");
xmlExport(getSharedPreferences("wifi", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "wifi");
serializer.startTag(null, "mobile");
xmlExport(getSharedPreferences("other", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "mobile");
serializer.startTag(null, "screen_wifi");
xmlExport(getSharedPreferences("screen_wifi", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "screen_wifi");
serializer.startTag(null, "screen_other");
xmlExport(getSharedPreferences("screen_other", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "screen_other");
serializer.startTag(null, "roaming");
xmlExport(getSharedPreferences("roaming", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "roaming");
serializer.startTag(null, "lockdown");
xmlExport(getSharedPreferences("lockdown", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "lockdown");
serializer.startTag(null, "apply");
xmlExport(getSharedPreferences("apply", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "apply");
serializer.startTag(null, "notify");
xmlExport(getSharedPreferences("notify", Context.MODE_PRIVATE), serializer);
serializer.endTag(null, "notify");
serializer.startTag(null, "filter");
filterExport(serializer);
serializer.endTag(null, "filter");
serializer.startTag(null, "forward");
forwardExport(serializer);
serializer.endTag(null, "forward");
serializer.endTag(null, "netguard");
serializer.endDocument();
serializer.flush();
}
@Override
public void serialize(OutputStream out, int format)
throws IOException, ParseException {
XmlSerializer serializer = null;
try {
serializer = factory.createSerializer();
} catch (XmlPullParserException e) {
throw new ParseException("Unable to create XmlSerializer.", e);
}
ByteArrayOutputStream printStream;
if (MapsClient.LOG_COMMUNICATION) {
printStream = new ByteArrayOutputStream();
serializer.setOutput(printStream, "UTF-8");
} else {
serializer.setOutput(out, "UTF-8");
}
serializer.startDocument("UTF-8", Boolean.FALSE);
declareEntryNamespaces(serializer);
serializer.startTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry");
if (MapsClient.LOG_COMMUNICATION) {
stream = printStream;
} else {
stream = out;
}
serializeEntryContents(serializer, format);
serializer.endTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry");
serializer.endDocument();
serializer.flush();
if (MapsClient.LOG_COMMUNICATION) {
Log.d("Request", printStream.toString());
out.write(printStream.toByteArray());
stream = out;
}
}
public static String createNodeXmlBody(Map<String, String> tags, String changesetId, double lat, double lon) throws Exception {
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
if (tags == null) return null;
/**
*
<osm>
<node changeset="12" lat="..." lon="...">
<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("", "changeset", changesetId);
xmlSerializer.attribute("", "lat", String.valueOf(lat));
xmlSerializer.attribute("", "lon", String.valueOf(lon));
//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();
}
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();
}
}
/**
* 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();
}
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);
}
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
}