search
HomeBackend DevelopmentXML/RSS Tutorialandroid sax creates xml file

android sax creates xml file

Feb 09, 2017 pm 02:02 PM
androidsaxxml file

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 xml files.

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 (www.php.cn)!


Statement
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
Scaling XML/RSS Processing: Performance Optimization TechniquesScaling XML/RSS Processing: Performance Optimization TechniquesApr 27, 2025 am 12:28 AM

When processing XML and RSS data, you can optimize performance through the following steps: 1) Use efficient parsers such as lxml to improve parsing speed; 2) Use SAX parsers to reduce memory usage; 3) Use XPath expressions to improve data extraction efficiency; 4) implement multi-process parallel processing to improve processing speed.

RSS Document Formats: Exploring RSS 2.0 and BeyondRSS Document Formats: Exploring RSS 2.0 and BeyondApr 26, 2025 am 12:22 AM

RSS2.0 is an open standard that allows content publishers to distribute content in a structured way. It contains rich metadata such as titles, links, descriptions, release dates, etc., allowing subscribers to quickly browse and access content. The advantages of RSS2.0 are its simplicity and scalability. For example, it allows custom elements, which means developers can add additional information based on their needs, such as authors, categories, etc.

Understanding RSS: An XML PerspectiveUnderstanding RSS: An XML PerspectiveApr 25, 2025 am 12:14 AM

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

RSS in XML: Decoding Tags, Attributes, and StructureRSS in XML: Decoding Tags, Attributes, and StructureApr 24, 2025 am 12:09 AM

RSS is an XML-based format used to publish and subscribe to content. The XML structure of an RSS file includes a root element, an element, and multiple elements, each representing a content entry. Read and parse RSS files through XML parser, and users can subscribe and get the latest content.

XML's Advantages in RSS: A Technical Deep DiveXML's Advantages in RSS: A Technical Deep DiveApr 23, 2025 am 12:02 AM

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function