Table of Contents
XML verification DTD " >XML verification DTD
Home Backend Development XML/RSS Tutorial XML concise tutorial (4)

XML concise tutorial (4)

Feb 18, 2017 pm 03:30 PM

Table of Contents


Development History

##XMLComparison with HTML Extensible

XML Syntax details compared to HTML

XML validation DTD

XMLSyntax structure

XMLNamespace

DOM4JRead and write configuration file

About SLT

XML verification DTD



As mentioned in the previous tutorial, the biggest role of XML is to store, transmit and exchange data. During this period, the correctness of XML was crucial, and corresponding measures were taken to ensure the correctness of XML. The correctness of

XML is divided into two aspects: one is the syntax of XML, and the other is the content of XML. People refer to XML with correct syntax as "well-formed" XML. For a well-formed XML document, we can only ensure that the format of the document conforms to the XML specification. In other words, we must ensure that the XML has no grammatical errors, but The relationship between elements and whether the values ​​of attributes are correct cannot be known. For a well-formed document, if it is only used in limited applications, such as as a configuration file in a self-developed system, or as a storage and transmission of data, it may be able to meet our application well. But if you want other users to understand or the system to use your XML document, or to exchange data, then you must ensure that the XML is "legal". In this way, it is necessary to provide an XML verification mechanism. The purpose is to ensure that the structure of the XML document we write and the XML document written by others are the same, the relationship between elements is correct, and the values ​​of attributes are correct. is in compliance with the requirements.

This mechanism has been provided for us in the XML standard, which is the DTD (Document Type Definition) we mentioned earlier. In other words, you can verify whether your own XML is "legal" XML through DTD.

We can define DTD directly in the XML document, or introduce external DTD files through URI. Although the internal DTD is convenient, it will increase the transmission burden due to the length of the document itself, and if multiple XML documents want to share a DTD, we need to add the DTD to each document, which is quite cumbersome. Therefore, the recommended approach is to define the DTD in a separate file and reference the external DTD file through the URI in the XML document.

The following demonstrates how to use a DTD file to verify the legitimacy of an XML file

test.xml file code

<?xml version="1.0" encoding="gb2312" standalone="no"?>
<!DOCTYPE student SYSTEM "test.dtd">
<!--这是XML文档-->
<student>
	<name>张三</name>
	<age>24</age>
</student>
Copy after login



代码解析:在第二行中将外部的DTD文档引入,用于判断XML是否合法。其中用的路径为相对路径,网上很多XML中引入的DTD是一个URI,无论是相对还是绝对的路径,总之只要XML能找到其对应的DTD就是可行的。

test.dtd文件代码

<!ELEMENT student (name,age)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ATTLIST student sex (man | woman) &#39;man&#39;>
Copy after login



代码解析:第一行至第三行定义了XML文件中的元素,以及元素之间的关系。在第四行定义了student属性中对sex的限制内容,其默认为man而且只能选取两个值man或者woman。

下面开始验证XML的合法性:



package ValidateXml;

import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ValidateXMLDTD {
    
    public static void main(String[] args) {
//       test1XML();
       test2XML();
    }
    
    public static void test1XML() {
        try {
        	InputSource ips=new InputSource();
        	ips.setSystemId("d:\\test.xml");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.parse(ips);
        System.out.println("xml 正确!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static void test2XML() {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            db.parse(new java.io.FileInputStream("d:\\test.xml"));
        System.out.println("xml 正确!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login



代码解析:上面的代码验证XML是否为合法,需要注意的是不要直接将XML读入到输入流中,那样的话会找不到相对路径下的DTD,调用test2XML会报错如下,如果调用test1XML则会正确验证XML。

直接用输入流读入的话XML寻找相对路径会在eclipse的环境下进行寻找DTD,如果用setSystemId进行设置的话会根据XML自己存在的目录中寻找DTD(参看具体解释),很显然后一种方式才是我们想要的。

通过DTD我们可以很容易的判断要验证的XML是否符合我们所定义的规范(元素之间的关系,属性的取值是否正确)但是如果要验证元素的内容DTD就无能为力了,于是人们研究了新的验证方法——Schema。就像人们远行一样,当对时间要求不苛刻的时候,火车便宜而且安全;当对时间有严格要求的时候,飞机也是不错的选择。根据实际需要改进技术,根据实际需要选择技术。量体裁衣,明智之举。

 以上就是XML简明教程(4) 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Import XML data into database using PHP Import XML data into database using PHP Aug 07, 2023 am 09:58 AM

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Use PHP and XML to process and display geolocation and map data Use PHP and XML to process and display geolocation and map data Aug 01, 2023 am 08:37 AM

Processing and displaying geolocation and map data using PHP and XML Overview: Processing and displaying geolocation and map data is a common requirement when developing web applications. PHP is a popular server-side programming language that can interact with data in XML format. This article explains how to use PHP and XML to process and display geolocation and map data, and provides some sample code. 1. Preparation: Before starting, you need to ensure that PHP and related extensions, such as Simple, are installed on the server

See all articles