下面列出了org.xmlpull.v1.XmlSerializer#setOutput ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 转换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;
}
/** The purpose of this test is to parse an XML attribute to an object's field. */
@Test
public void testParse_enumAttributeType() throws Exception {
XmlEnumTest.AnyTypeEnumAttributeOnly xml = new XmlEnumTest.AnyTypeEnumAttributeOnly();
XmlPullParser parser = Xml.createParser();
parser.setInput(new StringReader(XML_ENUM_ATTRIBUTE_ONLY));
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
Xml.parseElement(parser, xml, namespaceDictionary, null);
assertNotNull(xml.attributeEnum);
assertEquals(xml.attributeEnum, AnyEnum.ENUM_1);
// serialize
XmlSerializer serializer = Xml.createSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.setOutput(out, "UTF-8");
namespaceDictionary.serialize(serializer, "any", xml);
assertEquals(XML_ENUM_ATTRIBUTE_ONLY, out.toString());
}
/**
* Private Method to handle standard parsing and mapping to {@link AnyTypeEnumElementOnly}.
*
* @param xmlString XML String that needs to be mapped to {@link AnyTypeEnumElementOnly}.
* @return returns the serialized string of the XML object.
* @throws Exception thrown if there is an issue processing the XML.
*/
private String testStandardXml(final String xmlString) throws Exception {
AnyTypeEnumElementOnly xml = new AnyTypeEnumElementOnly();
XmlPullParser parser = Xml.createParser();
parser.setInput(new StringReader(xmlString));
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
Xml.parseElement(parser, xml, namespaceDictionary, null);
assertNotNull(xml.elementEnum);
assertEquals(xml.elementEnum, AnyEnum.ENUM_2);
// serialize
XmlSerializer serializer = Xml.createSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.setOutput(out, "UTF-8");
namespaceDictionary.serialize(serializer, "any", xml);
return out.toString();
}
public void testSerialize_emptyMapNsUndeclared() throws Exception {
ImmutableMap<String, String> map = ImmutableMap.of();
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.createSerializer();
serializer.setOutput(writer);
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "entry", map);
assertEquals(EXPECTED_EMPTY_MAP_NS_UNDECLARED, writer.toString());
}
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();
}
/** 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);
}
/**
* Writes services of a specified user to the file.
*/
private void writePersistentServicesLocked(UserServices<V> user, int userId) {
if (mSerializerAndParser == null) {
return;
}
AtomicFile atomicFile = createFileForUser(userId);
FileOutputStream fos = null;
try {
fos = atomicFile.startWrite();
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, "services");
for (Map.Entry<V, Integer> service : user.persistentServices.entrySet()) {
out.startTag(null, "service");
out.attribute(null, "uid", Integer.toString(service.getValue()));
mSerializerAndParser.writeAsXml(service.getKey(), out);
out.endTag(null, "service");
}
out.endTag(null, "services");
out.endDocument();
atomicFile.finishWrite(fos);
} catch (IOException e1) {
Log.w(TAG, "Error writing accounts", e1);
if (fos != null) {
atomicFile.failWrite(fos);
}
}
}
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
}
}
public void testSerialize_emptyMap() throws Exception {
ImmutableMap<String, String> map = ImmutableMap.of();
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.createSerializer();
serializer.setOutput(writer);
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
namespaceDictionary.set("", Atom.ATOM_NAMESPACE);
namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "entry", map);
assertEquals(EXPECTED_EMPTY_MAP, writer.toString());
}
public static String createChangesetXmlBody(Map<String, String> tags) throws Exception {
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
if (tags == null) return null;
/**
*
<osm>
<changeset>
<tag k="created_by" v="JOSM 1.61"/>
<tag k="comment" v="Just adding some streetnames"/>
...
</changeset>
...
</osm>
*/
xmlSerializer.setOutput(writer);
// start DOCUMENT
xmlSerializer.startDocument("UTF-8", true);
// open tag: <osm>
xmlSerializer.startTag("", "osm");
// open tag: <changeset>
xmlSerializer.startTag("", "changeset");
//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("", "changeset");
// close tag: </osm>
xmlSerializer.endTag("", "osm");
// end DOCUMENT
xmlSerializer.endDocument();
return writer.toString();
}
/**
* 获取手机短信并保存到xml中
* <p>需添加权限 {@code <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>}</p>
* <p>需添加权限 {@code <uses-permission android:name="android.permission.READ_SMS"/>}</p>
*/
public static void getAllSMS() {
// 1.获取短信
// 1.1获取内容解析者
ContentResolver resolver = Utils.getContext().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();
}
}
/** The purpose of this test is to map an XML with an Array of {@link XmlTest.AnyType} objects. */
@SuppressWarnings("unchecked")
@Test
public void testParseMultiGenericWithClassTypeGeneric() throws Exception {
MultiGenericWithClassTypeGeneric xml = new MultiGenericWithClassTypeGeneric();
XmlPullParser parser = Xml.createParser();
parser.setInput(new StringReader(MULTI_TYPE_WITH_CLASS_TYPE));
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
Xml.parseElement(parser, xml, namespaceDictionary, null);
// check type
GenericXml[] rep = xml.rep;
assertNotNull(rep);
assertEquals(3, rep.length);
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[0].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content1",
((ArrayMap<String, String>) (rep[0].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[1].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content2",
((ArrayMap<String, String>) (rep[1].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[2].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content3",
((ArrayMap<String, String>) (rep[2].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
// serialize
XmlSerializer serializer = Xml.createSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.setOutput(out, "UTF-8");
namespaceDictionary.serialize(serializer, "any", xml);
assertEquals(MULTI_TYPE_WITH_CLASS_TYPE, out.toString());
}
/** The purpose of this test is to map an XML with an Array of {@link XmlTest.AnyType} objects. */
@SuppressWarnings("unchecked")
@Test
public void testParseMultiGenericWithClassType() throws Exception {
MultiGenericWithClassType xml = new MultiGenericWithClassType();
XmlPullParser parser = Xml.createParser();
parser.setInput(new StringReader(MULTI_TYPE_WITH_CLASS_TYPE));
XmlNamespaceDictionary namespaceDictionary = new XmlNamespaceDictionary();
Xml.parseElement(parser, xml, namespaceDictionary, null);
// check type
GenericXml[] rep = xml.rep;
assertNotNull(rep);
assertEquals(3, rep.length);
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[0].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content1",
((ArrayMap<String, String>) (rep[0].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[1].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content2",
((ArrayMap<String, String>) (rep[1].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
assertEquals(
"text()",
((ArrayMap<String, String>) (rep[2].values().toArray(new ArrayList[] {})[0].get(0)))
.getKey(0));
assertEquals(
"content3",
((ArrayMap<String, String>) (rep[2].values().toArray(new ArrayList[] {})[0].get(0)))
.getValue(0));
// serialize
XmlSerializer serializer = Xml.createSerializer();
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.setOutput(out, "UTF-8");
namespaceDictionary.serialize(serializer, "any", xml);
assertEquals(MULTI_TYPE_WITH_CLASS_TYPE, out.toString());
}
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();
}
/**
* Write all account information to the account file.
*/
private void writeAccountInfoLocked() {
if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
}
FileOutputStream fos = null;
try {
fos = mAccountInfoFile.startWrite();
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, "accounts");
out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
// Write the Sync Automatically flags for each user
final int M = mMasterSyncAutomatically.size();
for (int m = 0; m < M; m++) {
int userId = mMasterSyncAutomatically.keyAt(m);
Boolean listen = mMasterSyncAutomatically.valueAt(m);
out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
}
final int N = mAuthorities.size();
for (int i = 0; i < N; i++) {
AuthorityInfo authority = mAuthorities.valueAt(i);
EndPoint info = authority.target;
out.startTag(null, "authority");
out.attribute(null, "id", Integer.toString(authority.ident));
out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
out.attribute(null, "account", info.account.name);
out.attribute(null, "type", info.account.type);
out.attribute(null, "authority", info.provider);
out.attribute(null, "syncable", Integer.toString(authority.syncable));
out.endTag(null, "authority");
}
out.endTag(null, "accounts");
out.endDocument();
mAccountInfoFile.finishWrite(fos);
} catch (java.io.IOException e1) {
Slog.w(TAG, "Error writing accounts", e1);
if (fos != null) {
mAccountInfoFile.failWrite(fos);
}
}
}
/**
* 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);
}
}
}
/**
* 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 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();
}
/**
* 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();
}