XML (extensible Tag language)

Source: Internet
Author: User
Tags gettext list of attributes tag name xml parser

XML one, Extend Markup languge (extensible Tag language)

tags are developed by the developer themselves (to be defined according to certain syntax)

1) Describe the data with the relationship (as a configuration file for the software): contains the relationship to be included

    <user>        <name>eric</name>        <password>123456</password>    </user>

Application scenario: Tomcat struts Hibernate Spring (three frames)

2) as a carrier of data (storing data, small "database")

Second, XML syntax

The XML file ends with an XML suffix name.

XML files need to be parsed using an XML parser. The browser has a built-in XML parser.

Label
语法: <student></student>  开始标签  标签体内容  结束标签                1)<student/> 或 <student></student> 空标签。没有标签体内容                2)xml标签名称区分大小写。                3)xml标签一定要正确配对。                4)xml标签名中间不能使用空格                5)xml标签名不能以数字开头                6)注意: 在一个xml文档中,有且仅有一个根标签
Property
语法: <Student name="eric">student</Student>            注意:                    1)属性值必须以引号包含,不能省略,也不能单双引号混用!!!                    2)一个标签内可以有多个属性,但不能出现重复的属性名!!!
Comments
语言: <!--  xml注释 -->
Requirements: Contacts System
联系人数据:编号 (唯一的) 姓名   年龄   电话 邮箱  QQ                  要求:                 contact.xml                    1)设计一个xml文件,用于存储联系人数据                    2)这个xml文件可以多个联系人。
Document Declaration
语法: <?xml version="1.0" encoding="utf-8"?>        version: xml的版本号        encoding: 解析xml文件时查询的码表(解码过程时查询的码表)注意:                1)如果在ecplise工具中开发xml文件,保存xml文件时自动按照文档声明的encoding来保存文                    件。                2)如果用记事本工具修改xml文件,注意保存xml文件按照文档声明的encoding的码表来保存。

* XML file

    ?<?xml version="1.0" encoding="utf-8"?>    <contactList>        <contact id="001">            <name>张三</name>            <age>20</age>            <phone>134222223333</phone>            <email>[email protected]</email>            <qq>432221111</qq>        </contact>        <contact id="002">            <name>李四</name>            <age>20</age>            <phone>134222225555</phone>            <email>[email protected]</email>            <qq>432222222</qq>        </contact>    </contactList>
XML parsing

In addition to the XML file to the developer, more cases are used to read the contents of the XML file. This is called XML parsing.

XML parsing method (different principle)

Dom parsing

Sax parsing

XML parsing tools
DOM解析原理:            1)JAXP (oracle-Sun公司官方)            2)JDOM工具(非官方)            3)Dom4J工具(非官方)            三大框架(默认读取xml的工具就是Dom4j)            .......SAX解析原理:            1)Sax解析工具(oracle-sun公司官方)
What is DOM parsing

Dom parsing principle: XML parser once the entire XML document loaded into memory,
Then build an object tree of document in memory, through the Document object,
Gets the node object on the tree, accessing (manipulating) the contents of the XML document through the Node object.

DOM4J Tools
非官方,不在jdk中。        使用步骤:            1)导入dom4j的核心包。 dom4j-1.6.1.jar            2)编写Dom4j读取xml文件代码

* Example

    /**     * 第一个Dom4j读取xml文档的例子     * @author APPle     *     */    public class Demo1 {        public static void main(String[] args) {            try {                //1.创建一个xml解析器对象                SAXReader reader = new SAXReader();                //2.读取xml文档,返回Document对象                Document doc = reader.read(new File("./src/contact.xml"));                System.out.println(doc);            } catch (DocumentException e) {                e.printStackTrace();                throw new RuntimeException(e);            }        }    }
DOMJ4 reading an XML file
  • Node:
  • Iterator  Element.nodeIterator();  //获取当前标签节点下的所有子节点
    • Case:

       /** * Get node information */@Testpublic void Test1 () throws exception{//1. Reads the XML document and returns the Document object Saxreade    R reader = new Saxreader ();    Document doc = Reader.read (new File ("./src/contact.xml"));    2.nodeIterator: Gets all child node objects under the current node (nodes that do not contain grandchildren) iterator<node> it = Doc.nodeiterator (); while (It.hasnext ()) {//Determines if there is a next element node node = It.next ();//Remove the element//continue to remove the sub-node below it//only the label node has child nodes//judgment            Whether the current node is a label node if (node instanceof Element) {Element Elem = (element) node;            Iterator<node> it2 = Elem.nodeiterator ();                while (It2.hasnext ()) {Node N2 = It2.next ();            System.out.println (N2.getname ()); }        }    }}
    • Case 2: Get all XML nodes (using recursion)

      /** * 遍历xml文档的所有节点 * @throws Exception */@Testpublic void test2() throws Exception{    //1.读取xml文档,返回Document对象    SAXReader reader = new SAXReader();    Document doc = reader.read(new File("./src/contact.xml"));    //得到根标签    Element rooElem = doc.getRootElement();    getChildNodes(rooElem);}/** * 获取 传入的标签下的所有子节点 * @param elem */private void getChildNodes(Element elem){    System.out.println(elem.getName());    //得到子节点    Iterator<Node> it = elem.nodeIterator();    while(it.hasNext()){        Node node = it.next();        //1.判断是否是标签节点        if(node instanceof Element){            Element el = (Element)node;            //递归            getChildNodes(el);        }    };}
  • Label:

  •  Element  Document.getRootElement();  //获取xml文档的根标签      Element   ELement.element("标签名") //指定名称的第一个子标签 Iterator<Element> Element.elementIterator("标签名");// 指定名称的所有子标签 List<Element>   Element.elements(); //获取所有子标签
    • Case:

      /** * Get label */@Testpublic void Test3 () throws exception{//1. Reads the XML document, returns the Document object Saxreader reader = new Saxreader ();    Document doc = Reader.read (new File ("./src/contact.xml"));    2. Get the root tag Element Rootelem = Doc.getrootelement ();    Gets the label name String named = Rootelem.getname ();    SYSTEM.OUT.PRINTLN (name);    3. Get the first sub-label of the specified name under the current label Element Contactelem = rootelem.element ("contact");    System.out.println (Contactelem.getname ());    4. Get all sub-labels for the specified name under the current label iterator<element> it = Rootelem.elementiterator ("contact");        while (It.hasnext ()) {Element elem = It.next ();    System.out.println (Elem.getname ());            }//5. Gets all the sub-tags under the current tab list<element> List = rootelem.elements ();  Traversal list Method//1) traditional for loop 2) enhanced for Loop 3) iterator for (int i=0;i<list.size (); i++) {Element E                = List.get (i);            System.out.println (E.getname ()); }//Get deeper labels (methods can only be obtained one layer at a) Element Nameelem= Doc.getrootelement ().            Element ("contact"). Element ("name");        System.out.println (Nameelem.getname ());                        }
  • Property:
  •  String   Element.attributeValue("属性名") //获取指定名称的属性值 Attribute    Element.attribute("属性名");//获取指定名称的属性对象     Attribute.getName()  //获取属性名称 Attibute.getValue()  //获取属性值 List<Attribute>     Element.attributes();  //获取所有属性对象 Iterator<Attribute>        Element.attibuteIterator(); //获取所有属性对象
      • Case:

         /** * Get Properties */@Testpublic void test4 () throws exception{//1. Reads the XML document and returns the Document object Saxr    Eader reader = new Saxreader ();    Document doc = Reader.read (new File ("./src/contact.xml"));    Gets the property: (The Label object where the property is first obtained, and then the property can be obtained)//1. Gets the Label object element Contactelem = Doc.getrootelement (). Element ("contact");    2. Get Property//2.1 property value of the specified name String idvalue = contactelem.attributevalue ("id");    System.out.println (Idvalue);    2.2 The Property object that gets the specified property name Attribute idattr = Contactelem.attribute ("id");    GetName: Attribute name GetValue: attribute value System.out.println (idattr.getname () + "=" + Idattr.getvalue ());    2.3 Get all Property objects, return the list collection list<attribute> list = Contactelem.attributes ();    Traverse Properties for (Attribute attr:list) {System.out.println (Attr.getname () + "=" +attr.getvalue ()); }}
  • Text:

    • Case:

      /** * 获取文本 */@Testpublic void test5() throws Exception{    //1.读取xml文档,返回Document对象    SAXReader reader = new SAXReader();    Document doc = reader.read(new File("./src/contact.xml"));    /**     * 注意: 空格和换行也是xml的内容     */    String content = doc.getRootElement().getText();    System.out.println(content);    //获取文本(先获取标签,再获取标签上的文本)    Element nameELem = doc.getRootElement().element("contact").element("name");    //1. 得到文本    String text = nameELem.getText();    System.out.println(text);    //2. 得到指定子标签名的文本内容    String text2 =     doc.getRootElement().element("contact").elementText("phone");    System.out.println(text2);}

  • Element.gettext (); Gets the text of the current label
    Element.elementtext ("tag name")//Gets the text content of the child label of the specified name of the current label
Exercise-Full read of XML document content
public class Demo3 {@Test public void Test () throws exception{//Read XML document Saxreader reader = new Saxre        Ader ();        Document doc = Reader.read (new File ("./src/contact.xml"));        Read root tag Element Rootelem = Doc.getrootelement ();        StringBuffer sb = new StringBuffer ();        Getchildnodes (ROOTELEM,SB);    System.out.println (Sb.tostring ()); }/** * Gets all child tags of the current label */private void Getchildnodes (Element elem,stringbuffer sb) {//system.out.printl        N (Elem.getname ());        Start label Sb.append ("<" +elem.getname ());        Get the list of attributes for the label list<attribute> attrs = Elem.attributes (); if (Attrs!=null) {for (Attribute attr:attrs) {//system.out.println (Attr.getname () + "=" +attr.get                Value ());            Sb.append ("" +attr.getname () + "=\" "+attr.getvalue () +" \ "");        }} sb.append (">");        Get text//string content = Elem.gettext (); SystEM.OUT.PRINTLN (content);        Iterator<node> it = Elem.nodeiterator ();            while (It.hasnext ()) {node node = It.next ();                Tag if (node instanceof element) {Element el = (element) node;            Getchildnodes (EL,SB);                }//text if (node instanceof text) {text text = (text) node;            Sb.append (Text.gettext ());    }}//end tag Sb.append ("</" +elem.getname () + ">"); }}
Encapsulating XML Document information into an object
/** * Encapsulates XML document information into an object * @author APPle * */public class Demo4 {public static void main (string[] args) throws Excepti                      on{list<contact> List = new arraylist<contact> ();            Reads XML, encapsulates object Saxreader reader = new Saxreader ();            Document doc = Reader.read (new File ("./src/contact.xml"));            Read the contact label iterator<element> it = Doc.getrootelement (). Elementiterator ("contact");                while (It.hasnext ()) {Element elem = It.next ();                Create Contact Contact contact = new Contact ();                Contact.setid (Elem.attributevalue ("id"));                Contact.setname (Elem.elementtext ("name"));                Contact.setage (Elem.elementtext ("Age"));                Contact.setphone (Elem.elementtext ("Phone"));                Contact.setemail (Elem.elementtext ("email"));                CONTACT.SETQQ (Elem.elementtext ("QQ"));            List.add (contact); }            for (contact contact:list) {System.out.println (contact); }        }}

XML (extensible Tag language)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.