XML Study Notes - recite Edition

Foreword

Systematic always wanted to learn XML, there is no time to learn, tonight a few hours out of school over XML. A few days to come and look back almost a back should remember more things, nothing difficult to understand.

XML data transfer format

The first chapter XML Overview

1.1 introduced

When we see the rapid progress of the development of XML standards, as well as a large number of software developers to adopt this standard when changing speed, really can not help but lament this is really amazing.

Currently, XML Web role to play in Asia not to have been the cornerstone of the Web as HTML.

XML is everywhere. XML is the most commonly used tools for transferring data between various applications, and is becoming increasingly popular in the field of information storage and description.

The main purpose of XML What?

Data transmission communication between the 1. program (can be cross-language transmission)

2. configuration file config.xml

3. store data, acting as a small database

Advantage:

Specification data format, having the structural data, easier to read and process

1.2 What is XML

Refers to Extensible Markup Language XML (eXtensible Markup Language), is designed to transmit and store data; XML to define their own tags, labels and self-descriptive name; XML is a W3C standard recommended storage data transfer.

The difference between HTML and XML?

1.html label can not be customized, XML only a custom label.

2.html syntax requirements are not strict, xml syntax for the very strict requirements, the label must be closed.

3.XML is designed to transmit and store data, which is the focus of the content data; was designed to display the HTML data, which is an external focus data presentation.

The basic syntax of XML Chapter II

2.1 syntax rules

1.XML documents must have a root element, the root element is the parent of all other elements.

2.XML declaration is an optional part of the first line if there is a need in the document

The so-called document declaration is to tell the parser current document format, version number, and encoding format.

3. All XML elements must be in pairs closing tag; non-closing tags is illegal, the parser will report an error, not without the normal resolution.

4.XML tags are case sensitive and must be consistent with the beginning and end tags.

5.XML label does not allow cross-nesting, that is, the parent-child relationship can not be cross-nested labels.

6.XML tag names do not use special characters, try to use only alphanumeric characters underlined.

7.XML comments in a comment in HTML syntax.

8. The special character entity reference &

In XML, some characters have a special meaning, if you put the character "<" on the XML element, the error occurs because the parser will use it as the beginning of a new element of <age>46 < 100 </age> this will generate an XML error;

To avoid errors, use entity references to replace special characters, use HTML formatting and physical character of the same

Entity Reference Character entity meaning
&lt < Less than -less than
&gt > Greater than -greater than
&amp & And --ampersand
&apos ' Single quotes -apostrophe
&quot " Double quotes -quotation mark

2.2 Element Properties

XML elements, can add one or more attributes, provided that

Attribute values ​​must use quotes (single or double quotes) to

The same naming conventions and naming attribute name element

Elements of the property is not allowed to repeat

Attribute is used to store data, but the actual development experience in HTML, property use them very convenient, but in XML, you should try to avoid using property because

1. attribute can not contain a plurality of values ​​(elements can)

2. The property value can not be structured data (elements can)

3. attributes are not easily expandable (for future changes)

4. The property is difficult to read and maintain.

Summary: The data on the attributes and child elements in the objective is to transmit data, and the sub-elements are more easily resolved, and better maintenance, and more ease of reference.

2.3 CDATA

To deal with a large number of special characters, entity references can no longer be dealt with (mostly too cumbersome, heavy workload) can use the data package can CDATA original format output.

format: <test><![CDATA[第一题题1:已知 c<4,d>5,问:c和d那个更好看? ]]> </test>

Entity references and CDATA use the opportunity of:

1. For the case where the content is relatively small, special characters can be directly replaced, use entity reference.

2. For more content, it is recommended using CDATA sections.

Chapter 3 Using PHP parsing XML documents

After PHP5 version, which provides a very, very powerful library, SimpleXML library, dedicated to the realization of an XML document parsing operation. PHP use this library to handle XML data.

3.1 XML parsing principle

When parsing XML total to go through three steps:

  1. Read an XML document into memory

2. DOM tree structure is formed (DOM tree structure of the document can be simply understood that the parent-child)

3. Generate SimpleXML objects

3.2 SimpleXML library

Syntax: simplexml_load_file ( 'test.xml');

<?xml version="1.0" encoding="UTF-8"?>
<user>
    <man>
    <name>aklman</name>
        <age>20</age>
            <sex>男</sex>
    </man>
    <man sex="男">
        <name>ak</name>
        <age>22</age>
    </man>
</user>
$xml=simplexml_load_file('test.xml');//引入文件并读取
var_dump($xml);//输出,输出个格式就是一个对象
1. If the current node is the object is read by -> be accessed;

2. If the node is currently read by the array to [] to be accessed;

3.3 traverse XML data

1.foreach loop through
$xml=simplexml_load_file('test.html);
foreach($xml->man as $v){
    echo 'Name:'.$v->name.'Age:'.$v->age.'<br>';
}
2.for loop through
$xml=simplexml_load_file('test.html);
$length=count($xml);
for($i=0;$i<$length;$i++){
    echo $xml->man[$i]->name;
}
When reading an attribute node XML attributes to be added to the parent node, PHP to parse
$xml=simplexml_load_file('test.xml');
echo $xml->man[1]->attributes()->sex;
//attributes()方法是用来获取节点属性,
//内存中节点属性存放在attributes中,它是一个以为数组,可以使用attributes()方法获取

3.4 SImpleXML add nodes

$xml=simplexml_load_file('test.html);
$man=
//创建添加子节点
$man = $xml->addChild('man');
//为节点添加属性
$man->addAttribute('sex','女');
//创建添加子节点及节点值
$man->addChild('name','aklman');
$man->addChild('age','23');
var_dump($xml);//打印,已经添加到内存
$xml->asXML('test1.xml');//保存数据进XML文件,没有文件,则创建;

3.5 Case

Queries mobile phone ownership to the case, sources of data aggregation network
<form action="03.5.php" method="get">
    <input type="text" name="num"><br>
    <input type="submit" value="提交">
</form>
//接受前台提交的数据
$tel = $_GET['num'];
//组装请求地址
$url = 'http://v.juhe.cn/telephone/index?telephoneNumber='.$tel.'&dtype=xml&format=&key=810c3b2c488bc37d5f521196d8799a7211';//地址已经打乱了,需要从聚合网购买
//发送请求并接受返回的数据
$s = file_get_contents($url);
// echo $s; //打印返回的XML数据
//使用 simplexml_load_string 函数读入并解析XML数据
$xml = simplexml_load_string($s);
//找到并打印我们想要的数据
echo '归属省:'.$xml->result->place->city111.'<hr>';
echo '归属城市:'.$xml->result->place->city.'<hr>';

Chapter IV Xpath language

4.1 Overview

XPath is a finding information in an XML document language, XPath can be used to traverse the elements and attributes in an XML document.

4.2 Use and grammar

Caution:

1. Use an absolute path for data query
$xml = simplexml_load_file('user.xml');
//按节点的绝对路径查找
$data = $xml->xpath('/user/man/name');//返回数组
foreach($data as $v){
    echo $v.'<hr>';
}
/*
*如果路径以斜线 / 开始, 那么该路径就表示到一个元素的绝对路径,
*绝对路径实现数据查询必须一级一级的查询下去,不能越级。
*/
2. Use a relative path for data query
$xml = simplexml_load_file('user.xml');
//按节点的相对路径查找
$data = $xml->xpath('//name');//返回数组
foreach($data as $v){
echo $v.'<hr>';
}
/*
*如果路径以双斜线 // 开头, 则表示选择文档中所有满足双斜线//之后规则的元素(无论层级关系)
*/
3. Use * to match all nodes
$xml = simplexml_load_file('user.xml');
//匹配man节点下的所有元素节点。
$data = $xml->xpath('//man/*');//返回数组
foreach($data as $v){
echo $v.'<hr>';
}
4. Use [] brackets in the form of a query to implement the data
$xml = simplexml_load_file('user.xml');
//匹配man节点下的最后一个节点。
$data = $xml->xpath('//man[last()]');//返回数组
var_dump($data);
echo $data[0]->name;
//man[1] : 获取第一个man元素
//man[last()]:获取最后一个man元素
//man[age > 200] :获取age>200的man节点
/*
*方块号里的表达式可以进一步的指定元素, 其中数字表示元素在选择集里的位置
*默认从1开始,而last()函数则表示选择集中的最后一个元素,括号内还可以放置表达式
*/
5. Use the property to get the element
$xml = simplexml_load_file('user.xml');
//匹配man节点下含有sex属性的节点。
$data = $xml->xpath('//man[@sex]');//返回数组
var_dump($data);
echo $data[0]->name;

Reference material

W3school
rookie tutorial
XML Application Programming Guide (2nd Edition)

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/11968915.html