search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Home Backend Development XML/RSS Tutorial android sax creates xml file

android sax creates xml file

Feb 17, 2017 pm 03:16 PM

The first two articles briefly explain the way sax parses xml and implement the parsing function. Next use sax to create the xml file.

Specifically how to use sax to create xml, add relevant comments in the program, or directly enter the code.


package cn.com.sax;

import java.io.OutputStream;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

import android.util.Log;

class SxaCreateXml {
	/**
	 * SAX方式生成XML
	 * 
	 * @param list
	 * @return
	 */
	public String saxToXml(OutputStream output) {
		String xmlStr = null;
		try {
			// 用来生成XML文件
			// 实现此接口的对象包含构建转换结果树所需的信息
			Result resultXml = new StreamResult(output);

			// 用来得到XML字符串形式
			// 一个字符流,可以用其回收在字符串缓冲区中的输出来构造字符串
			StringWriter writerStr = new StringWriter();
			// 构建转换结果树所需的信息。
			Result resultStr = new StreamResult(writerStr);

			// 创建SAX转换工厂
			SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory
					.newInstance();
			// 转换处理器,侦听 SAX ContentHandler
			// 解析事件,并将它们转换为结果树 Result
			TransformerHandler th = sff.newTransformerHandler();
			// 将源树转换为结果树
			Transformer transformer = th.getTransformer();
			// 设置字符编码
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			// 是否缩进
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");

			// 设置与用于转换的此 TransformerHandler 关联的 Result
			// 注:这两个th.setResult不能同时启用
			 th.setResult(resultXml);
//			 th.setResult(resultStr);
			//创建根元素<calsses>,并设置其属性为空
			th.startDocument();
			AttributesImpl attr = new AttributesImpl();
			th.startElement("", "calsses", "calsses", attr);
			
			//创建一级子元素<group>,并设置其属性
			attr.clear();
			attr.addAttribute("","name", "name", "", "一年级");
			attr.addAttribute("","num", "num", "", "10");
			th.startElement("", "", "group", attr);
			//创建二级子元素<person>,并设置其属性
			attr.clear();
			attr.addAttribute("","name", "name", "", "小明");
			attr.addAttribute("","age", "age", "", "7");
			th.startElement("", "", "person", attr);
			//创建三级子元素<chinese>,并设置其值
			attr.clear();
			th.startElement("", "", "chinese", attr);
			th.characters("语文90".toCharArray(), 0, "语文90".length());
			th.endElement("", "", "chinese");
			//创建三级子元素<english>,并设置其值
			th.startElement("", "", "english", attr);
			th.characters("英语80".toCharArray(), 0, "英语80".length());
			th.endElement("", "", "english");
			
			th.endElement("", "", "person");
			th.endElement("", "", "group");
			th.endElement("", "calsses", "calsses");
			th.endDocument();
			xmlStr = writerStr.getBuffer().toString();
		} catch (TransformerConfigurationException e) {
			Log.e("TEST", ""+e.toString());
		} catch (SAXException e) {
			Log.e("TEST", ""+e.toString());
		} catch (Exception e) {
			Log.e("TEST", ""+e.toString());
		}
		Log.e("TEST","生成的"+xmlStr);
		return xmlStr;
	}
}


Call this method to achieve the purpose of creating an xml file.


new SxaCreateXml().saxToXml(openFileOutput("sax.xml",  Context.MODE_PRIVATE));


The generated sax.xml file is still in the data/data/cn.xxx.xxx/files folder.



<?xml version="1.0" encoding="UTF-8"?>
<calsses>
<group name="一年级" num="10">
<person name="小明" age="7">
<chinese>语文90</chinese>
<english>英语80</english>
</person>
</group>
</calsses>

The above is the content of the xml file created by android sax. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com )!




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tencent Yuanbao official website latest login entrance Tencent Yuanbao AI usage address Tencent Yuanbao official website latest login entrance Tencent Yuanbao AI usage address Feb 04, 2026 pm 06:06 PM

The latest login portal of Tencent Yuanbao official website is https://yuanbao.tencent.com/, which is a direct web portal deployed by Tencent. It supports mainstream browsers without installation and has features such as lightweight loading, multi-round conversation memory, and barrier-free access.

What is a 'hackathon” champion in the cryptocurrency industry? What do they gain? What is a 'hackathon” champion in the cryptocurrency industry? What do they gain? Jan 31, 2026 pm 02:18 PM

The champion of the currency circle's "Hackerathon" is the one with the highest comprehensive score through on-chain testing, K verification, and anonymous review. He or she will enjoy cash rewards (such as $75,000 Grant), token incentives (such as 75,000 flash tokens), and ecological rights (such as conference speeches, protocol access, and application listings).

How to combine HTML5 password with fingerprint verification_Integrate biometrics to provide a convenient method [Method] How to combine HTML5 password with fingerprint verification_Integrate biometrics to provide a convenient method [Method] Feb 07, 2026 am 09:10 AM

HTML5 does not support direct calls to the fingerprint sensor, and biometric login must be implemented in an HTTPS environment through WebAuthenticationAPI (navigator.credentials); it is only a pure front-end control and does not have access to the hardware. The browser sandbox mechanism prohibits scripts from reading fingerprints or triggering the sensor.

How to enable Android subsystem developer mode in Win11_Windows11 WSA settings debugging How to enable Android subsystem developer mode in Win11_Windows11 WSA settings debugging Jan 26, 2026 pm 12:24 PM

If you have turned on the WSA developer mode, you can install the APK through ADB. The operations include: 1. Turn on the developer mode in WSA "Advanced Settings" and confirm the IP and port; 2. If the switch is gray, use PowerShell to execute the Reset-AppxPackage and adb restart commands; 3. Use adbconnect to verify whether the connection is successful.

How to accurately pass and summarize multi-level product prices in nested RecyclerView How to accurately pass and summarize multi-level product prices in nested RecyclerView Feb 06, 2026 pm 08:54 PM

This article explains in detail how to correctly calculate and return the total price of each store (including the main price of the product, the price and quantity of add-ons) in the three-layer nested RecyclerView (store → product → add-on) structure to avoid the problem of value loss caused by the Adapter life cycle and data binding timing.

How to turn on low blue light mode in Thunderbird AirPlus_Turn on eye protection mode in Thunderbird AirPlus [Protection] How to turn on low blue light mode in Thunderbird AirPlus_Turn on eye protection mode in Thunderbird AirPlus [Protection] Feb 07, 2026 pm 07:16 PM

Thunderbird AirPlus can turn on the low blue light mode in four ways: 1. Press and hold the right dial on the temple for 2 seconds to quickly start and stop; 2. Adjust the "Display and Brightness → Eye Protection Mode" in the magic box settings; 3. ThunderbirdVisionApp remote synchronization configuration; 4. HDMI source device linkage to trigger hardware-level protection.

What is SAX parsing XML? The difference between SAX and DOM What is SAX parsing XML? The difference between SAX and DOM Feb 05, 2026 am 06:54 AM

SAX parsing is an event-driven streaming XML processing method that triggers callbacks while reading. It has constant memory usage and is suitable for large files or memory-limited scenarios. DOM loads XML as a memory tree, which supports random access but consumes large memory.

Application of html statements_Comparison of loading speed of html statements on different devices [Introduction] Application of html statements_Comparison of loading speed of html statements on different devices [Introduction] Feb 07, 2026 am 09:39 AM

HTML loading speed is not determined by tag type, but depends on resource volume, network transmission, browser parsing efficiency and device performance differences; mobile terminals need to avoid blocking scripts, inline styles, deep nesting and uncompressed HTML.

Related articles