안드로이드 돔 방식으로 XML 생성

黄舟
풀어 주다: 2017-02-09 14:09:02
원래의
1947명이 탐색했습니다.

android dom으로 xml을 파싱하는 방법에 대한 글에서는 xml을 파싱하는 dom의 응용을 간략하게 소개합니다. 오늘은 원문을 바탕으로 안드로이드에서 xml을 생성하기 위해 dom을 적용하는 방법에 대해 이야기해보겠습니다.

우선 생성된 파일은 /data/data/cn.com.xxx(현재 패키지 이름)/files에 저장됩니다.

생성된 xml 파일은 다음과 같이 생성됩니다.

<?xml version="1.0" encoding="utf-8"?>  
<classes>  
    <group name="一年级" num="10">  
        <person name="小明" age="7">  
            <chinese>语文90</chinese>  
            <english>英语80</english>  
        </person>  
    </group>  
</classes>
로그인 후 복사

android dom parsing xml 기사에 있는 메서드를 직접 사용하여 일부 수정해 보세요.

// 从assets文件夹下获取文件 转换成输入流  
//          inStream = this.getResources().getAssets().open(fileName);  
//          doc = docBuilder.parse(inStream);  
            InputStream fosStream = openFileInput(fileName);  
            doc = docBuilder.parse(fosStream);
로그인 후 복사


동시에 fileName 획득 방법은

String[] fileNames = getFilesDir().list();
로그인 후 복사
String fileName = fileNames[0];
로그인 후 복사


파싱된 결과는

안드로이드 돔 방식으로 XML 생성<입니다. 🎜>

다음은 xml 파일을 생성하는 코드입니다.


private void createXmlFile(){  
          
        try {  
            DocumentBuilderFactory factory = DocumentBuilderFactory  
                    .newInstance();  
            DocumentBuilder builder = factory.newDocumentBuilder();  
            Document doc  = builder.newDocument();  
            //创建xml根元素  
            Element rootEle = doc.createElement("classes");  
            doc.appendChild(rootEle);  
            //创建xml二级元素  
            Element groupEle = doc.createElement("group");  
            groupEle.setAttribute("name", "一年级");  
            groupEle.setAttribute("num", "10");  
            //创建xml person元素  
            Element personEle = doc.createElement("person");  
            //personEle 的属性和属性值  
            personEle.setAttribute("name", "小明");  
            personEle.setAttribute("age", "7");  
            //创建personELe的子元素  
            Element chinese = doc.createElement("chinese");  
            //创建personELe的子元素的值  
            chinese.appendChild(doc.createTextNode("语文90"));  
            personEle.appendChild(chinese);  
            Element english = doc.createElement("english");  
            english.appendChild(doc.createTextNode("英语80"));  
            personEle.appendChild(english);  
              
            groupEle.appendChild(personEle);  
            rootEle.appendChild(groupEle);  
              
            TransformerFactory tf = TransformerFactory.newInstance();  
            Transformer transformer = tf.newTransformer();  
              
            DOMSource source = new DOMSource(doc);  
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
            transformer.setOutputProperty(OutputKeys.INDENT, "no");  
            //创建文件存放在 /data/data/cn.xxx.xxx(当前包)/files   
            FileOutputStream fos = openFileOutput("Dom.xml", Context.MODE_PRIVATE);  
            //创建文件存放在 /data/data/cn.xxx.xxx(当前包)/cache  
//          FileOutputStream fos = Op  
            PrintWriter pw = new PrintWriter(fos);  
            StreamResult result = new StreamResult(pw);  
            transformer.transform(source, result);  
              
            System.out.println("生成XML文件成功!");  
        } catch (ParserConfigurationException e) {  
            System.out.println(e.getMessage());  
        } catch (TransformerConfigurationException e) {  
            System.out.println(e.getMessage());  
        } catch (TransformerException e) {  
            System.out.println(e.getMessage());  
        } catch (FileNotFoundException e) {  
            System.out.println(e.getMessage());  
        }  
          
    }
로그인 후 복사
위는 android dom 방식으로 xml을 생성하는 내용입니다. 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 주목해주세요!


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!