文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Android创建与解析XML(二)——详解Dom方式

2022-06-06 05:40

关注

1. Dom概述

Dom方式创建XML,应用了标准xml构造器 javax.xml.parsers.DocumentBuilder 来创建 XML 文档,需要导入以下内容


javax.xml.parsers
javax.xml.parsers.DocumentBuilder 
javax.xml.parsers.DocumentBuilderFactory 
javax.xml.parsers.ParserConfigurationException;
javax.xml.transform
javax.xml.transform.TransformerFactory 
javax.xml.transform.Transformer 
javax.xml.transform.dom.DOMSource 
javax.xml.transform.stream.StreamResult 
javax.xml.transform.OutputKeys;
javax.xml.transform.TransformerFactoryConfigurationError;
javax.xml.transform.TransformerConfigurationException;
javax.xml.transform.TransformerException;
org.w3c.dom 
org.w3c.dom.Document;
org.w3c.dom.Element;
org.w3c.dom.Node;
org.w3c.dom.DOMException;
org.w3c.dom.NodeList;
org.xml.sax.SAXException;

创建和解析xml的效果图:

2、Dom 创建 XML

Dom,借助 javax.xml.parsers.DocumentBuilder,可以创建 org.w3c.dom.Document 对象。

使用来自 DocumentBuilderFactory 的 DocumentBuilder 对象在 Android 设备上创建与解析 XML 文档。您将使用 XML pull 解析器的扩展来解析 XML 文档。


 
public String domCreateXML() { 
  String xmlWriter = null; 
  Person []persons = new Person[3];    // 创建节点Person对象 
  persons[0] = new Person(1, "sunboy_2050", "//www.jb51.net/"); 
  persons[1] = new Person(2, "baidu", "http://wwwbaiducom"); 
  persons[2] = new Person(3, "google", "http://wwwgooglecom"); 
  try { 
    DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); 
    DocumentBuilder builder = factorynewDocumentBuilder(); 
    Document doc = buildernewDocument(); 
    Element eleRoot = doccreateElement("root"); 
    eleRootsetAttribute("author", "homer"); 
    eleRootsetAttribute("date", "2012-04-26"); 
    docappendChild(eleRoot); 
    int personsLen = personslength; 
    for(int i=0; i<personsLen; i++) { 
      Element elePerson = doccreateElement("person"); 
      eleRootappendChild(elePerson); 
      Element eleId = doccreateElement("id"); 
      Node nodeId = doccreateTextNode(persons[i]getId() + ""); 
      eleIdappendChild(nodeId); 
      elePersonappendChild(eleId); 
      Element eleName = doccreateElement("name"); 
      Node nodeName = doccreateTextNode(persons[i]getName()); 
      eleNameappendChild(nodeName); 
      elePersonappendChild(eleName); 
      Element eleBlog = doccreateElement("blog"); 
      Node nodeBlog = doccreateTextNode(persons[i]getBlog()); 
      eleBlogappendChild(nodeBlog); 
      elePersonappendChild(eleBlog); 
    } 
    Properties properties = new Properties(); 
    propertiessetProperty(OutputKeysINDENT, "yes"); 
    propertiessetProperty(OutputKeysMEDIA_TYPE, "xml"); 
    propertiessetProperty(OutputKeysVERSION, "0"); 
    propertiessetProperty(OutputKeysENCODING, "utf-8"); 
    propertiessetProperty(OutputKeysMETHOD, "xml"); 
    propertiessetProperty(OutputKeysOMIT_XML_DECLARATION, "yes"); 
    TransformerFactory transformerFactory = TransformerFactorynewInstance(); 
    Transformer transformer = transformerFactorynewTransformer(); 
    transformersetOutputProperties(properties); 
    DOMSource domSource = new DOMSource(docgetDocumentElement()); 
    OutputStream output = new ByteArrayOutputStream(); 
    StreamResult result = new StreamResult(output); 
    transformertransform(domSource, result); 
    xmlWriter = outputtoString(); 
  } catch (ParserConfigurationException e) {   // factorynewDocumentBuilder 
    eprintStackTrace(); 
  } catch (DOMException e) {           // doccreateElement 
    eprintStackTrace(); 
  } catch (TransformerFactoryConfigurationError e) {   // TransformerFactorynewInstance 
    eprintStackTrace(); 
  } catch (TransformerConfigurationException e) {   // transformerFactorynewTransformer 
    eprintStackTrace(); 
  } catch (TransformerException e) {       // transformertransform 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
  savedXML(fileName, xmlWritertoString()); 
  return xmlWritertoString(); 
} 

运行结果:

3、Dom 解析 XML

Dom方式,解析XML是创建XML的逆过程,主要用到了builder.parse(is)进行解析,然后通过Tag、NodeList、Element、childNotes等得到Element和Node属性或值。


 
public String domResolveXML() { 
  StringWriter xmlWriter = new StringWriter(); 
  InputStream is= readXML(fileName); 
  try { 
    DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance(); 
    DocumentBuilder builder = factorynewDocumentBuilder(); 
    Document doc = builderparse(is); 
    docgetDocumentElement()normalize(); 
    NodeList nlRoot = docgetElementsByTagName("root"); 
    Element eleRoot = (Element)nlRootitem(0); 
    String attrAuthor = eleRootgetAttribute("author"); 
    String attrDate = eleRootgetAttribute("date"); 
    xmlWriterappend("root")append("\t\t"); 
    xmlWriterappend(attrAuthor)append("\t"); 
    xmlWriterappend(attrDate)append("\n"); 
    NodeList nlPerson = eleRootgetElementsByTagName("person"); 
    int personsLen = nlPersongetLength(); 
    Person []persons = new Person[personsLen]; 
    for(int i=0; i<personsLen; i++) { 
      Element elePerson = (Element) nlPersonitem(i);   // person节点 
      Person person = new Person();            // 创建Person对象 
      NodeList nlId = elePersongetElementsByTagName("id"); 
      Element eleId = (Element)nlIditem(0); 
      String id = eleIdgetChildNodes()item(0)getNodeValue(); 
      personsetId(IntegerparseInt(id)); 
      NodeList nlName = elePersongetElementsByTagName("name"); 
      Element eleName = (Element)nlNameitem(0); 
      String name = eleNamegetChildNodes()item(0)getNodeValue(); 
      personsetName(name); 
      NodeList nlBlog = elePersongetElementsByTagName("blog"); 
      Element eleBlog = (Element)nlBlogitem(0); 
      String blog = eleBloggetChildNodes()item(0)getNodeValue(); 
      personsetBlog(blog); 
      xmlWriterappend(persontoString())append("\n"); 
      persons[i] = person; 
    } 
  } catch (ParserConfigurationException e) {   // factorynewDocumentBuilder 
    eprintStackTrace(); 
  } catch (SAXException e) {   // builderparse 
    eprintStackTrace(); 
  } catch (IOException e) {    // builderparse 
    eprintStackTrace(); 
  } catch (Exception e) { 
    eprintStackTrace(); 
  } 
  return xmlWritertoString(); 
} 

运行结果:

4、Person类

Person类,是创建xml的单位实例,基于Java面向对象定义的一个类


public class Person { 
  private int id; 
  private String name; 
  private String blog; 
  public Person() { 
    thisid = -1; 
    thisname = ""; 
    thisblog = ""; 
  } 
  public Person(int id, String name, String blog) { 
    thisid = id; 
    thisname = name; 
    thisblog = blog; 
  } 
  public Person(Person person) { 
    thisid = personid; 
    thisname = personname; 
    thisblog = personblog; 
  } 
  public Person getPerson(){ 
    return this; 
  } 
  public void setId(int id) { 
    thisid = id; 
  } 
  public int getId(){ 
    return thisid; 
  } 
  public void setName(String name) { 
    thisname = name; 
  } 
  public String getName() { 
    return thisname; 
  } 
  public void setBlog(String blog) { 
    thisblog = blog; 
  } 
  public String getBlog() { 
    return thisblog; 
  } 
  public String toString() { 
    return "Person \nid = " + id + "\nname = " + name + "\nblog = " + blog + "\n"; 
  } 
} 
您可能感兴趣的文章:Android 创建与解析XML(五)——详解Dom4j方式Android开发之DOM解析xml文件的方法Android编程解析XML方法详解(SAX,DOM与PULL)Android应用中使用DOM方式解析XML格式数据的基本方法Android解析XML的三种方式SAX、Pull、Dom详解Android之解析XML文件三种方式(DOM,PULL,SAX)Android利用SAX对XML进行增删改查操作详解Android利用Dom对XML进行增删改查操作详解


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     801人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     348人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     311人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     432人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     220人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯