Extensible Markup Language XML (intermittent drizzle)

Source: Internet
Author: User
Tags xml parser

XML brief

XML is used to describe data and is a powerful tool for the current process of structured document information. It is independent of the development platform of the operating system programming language and can realize the data interaction between different systems.

XML file Structure:

1 <?xml version= "1.0" encoding= "UTF-8"? >2 <people>3     <Name> name </name>4     <Sex> Sex </sex>5 </people>

The first line in the code is the XML declaration, which is generally in the top row of the XML document. It consists of two parts:

Version: The document conforms to the XML1.0 specification.

Encoding: Document character encoding, default is "UTF-8".

<!--Comment---comment syntax.

There are 3 features of the XML language:

Each pair of tags in 1.XML is often referred to as nodes, they are paired and must appear in pairs to describe what the node stores. Stores information for this node in a node.

Each node in the 2.XML that describes the data can be freely scaled and scaled vertically, i.e. it can be scaled down or scaled inward (nested).

The nodes in the 3.XML file are strictly case sensitive. Example:<name> name </Name> and <name> name </name> These two nodes have the same content, but the node name is different, that is, two nodes.

manipulating XML files in C #

Manipulating and parsing XML files in C # is a 6-step process:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.threadi Ng. Tasks;               6 using System.Xml;             1. Introduction of Namespace 7 8 namespace Demo 9 {Ten class Program11 {static void Main (string[] args) 13 {14                                XmlDocument doc = new XmlDocument (); 2. Create an XML file object, Doc.                                               Load ("Path.xml"); 3. Read the structure of the entire XML file from the specified path XmlNode nodes = Doc.                                DocumentElement; 4. Get the root node of the XML file, XmlNode node in nodes. ChildNodes)//5. Iterates over the child nodes of the root node. {String name = node["Name"].                           InnerText; 6. Get the contents of the XML file node. String sex = node["Sex"]. Innertext;21 Console.WriteLine ("Name: {0}, Gender: {1}", name, sex);}23}24}25} 

XmlDocument object:

Represents the entire XML document, which uses the Load method to read the specified XML file into the XmlDocument object, and the parameters of the Load method are the path to the XML document.

The DocumentElement property is used to get the root node.

XmlNode object:

The XmlNode object represents a node in an XML.
The ChildNodes property is used to get all child nodes of the specified node.

The Name property can get the names of the current node. Example:<name> name </name> get name.

The Inner Text property is used to get the value of the current node. Example:<name> name </name> get name.

The Attributes property can get the attributes of the current node. Example: <name type= "Dog" > Name </name> attributes["type"] get dog.

Note: The ChildNodes property represents all child nodes of the current node, where all child nodes represent a collection of current child nodes.

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();  //获取当前标签节点下的所有子节点
    • /** * Get node information */@Testpublic void Test1 () throws exception{//1. Read XML document, return Document Object Saxreader 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);        }    };}

Extensible Markup Language XML (intermittent drizzle)

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.