search

XML concise tutorial (7)

Feb 18, 2017 pm 03:39 PM

Table of Contents


Development History

##XMLComparison with HTML Extensible

XML Syntax details compared with HTML

XML validation DTD

XMLNamespace

XMLSyntax structure

XML Validation Schema

DOM4JRead and write configuration file

About SLT

XML Validation Schema



##As mentioned in the previous article Yes, through DTD we can easily judge whether the XML to be verified conforms to the specifications we have defined (the relationship between elements, whether the values ​​of attributes are correct), but if we want to verify the content of elements, DTD is powerless, so people study A new verification method - Schema.

In addition to the above advantages,

Schema is even more impressive than DTD The exciting thing is that it is itself a well-formed XML document, so it is very easy to write Schema. Compared with DTD which has its own independent syntax, it is very difficult to write and maintain. A Schema file is an XML file, so the corresponding

Schema

## written by XML The process of # is to write XML against XML. In this case, it is very easy to write Schema. The following demonstrates how to write the corresponding Schema against XMLOriginal XML file (test2.xml)

<?xml version="1.0"encoding="ISO-8859-1"?>
 
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
 <orderperson>George Bush</orderperson>
 <shipto>
  <name>John Adams</name>
  <address>Oxford Street</address>
  <city>London</city>
  <country>UK</country>
 </shipto>
 <item>
  <title>Empire Burlesque</title>
  <note>Special Edition</note>
  <quantity>1</quantity>
  <price>10.90</price>
 </item>
 <item>
  <title>Hide your heart</title>
  <quantity>1</quantity>
  <price>9.90</price>
 </item>
</shiporder>




##For the above XML Let’s start creating a Schema. The principle to follow is how to write the original XML and then describe the corresponding Schema, just like you are face to face with a person. The description is the same.

Schema code is as follows (shiporder.xsd)

##

 <?xml version="1.0"encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="shiporder">
 <xs:complexType>
  <xs:sequence>
   <xs:element name="orderperson"type="xs:string"/>
   <xs:element name="shipto">
    <xs:complexType>
     <xs:sequence>
      <xs:elementname="name" type="xs:string"/>
      <xs:elementname="address" type="xs:string"/>
      <xs:elementname="city" type="xs:string"/>
      <xs:elementname="country" type="xs:string"/>
     </xs:sequence>
    </xs:complexType>
   </xs:element>
   <xs:element name="item"maxOccurs="unbounded">
    <xs:complexType>
     <xs:sequence>
      <xs:elementname="title" type="xs:string"/>
      <xs:elementname="note" type="xs:string" minOccurs="0"/>
      <xs:elementname="quantity" type="xs:positiveInteger"/>
      <xs:element name="price"type="xs:decimal"/>
     </xs:sequence>
    </xs:complexType>
   </xs:element>
  </xs:sequence>
  <xs:attribute name="orderid"type="xs:string" use="required"/>
 </xs:complexType>
</xs:element>
 
</xs:schema>


Code analysis:

The first line is all

XML The statement needs no elaboration.

The second line does this

XML(Schema itself is a XML) defines a namespace.

Starting from the fourth line are some requirements for the original

XML:

首先定义了根元素为shiporder(行4),其次因为shiporder元素有一个属性,其中包含其他的元素所以其为复合类型(行5)。然后通过sequence元素按照顺序包围其子元素(行10---15),描述元素的名称以及元素的类型(行11----14),如果需要描述元素的限制条件(行22)。描述根元素的属性,由于是必选属性所以选择required关键字,需要注意的是这个属性必须放在最后(行29

通过Schema验证XML的代码和前面文章中的DTD验证大同小异,代码如下:

package ValidateXml;
 
import java.io.File;
import java.io.IOException;
 
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
 
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
 
importcom.sun.org.apache.xml.internal.utils.DefaultErrorHandler;
 
public class XmlValidator
{
    private String xsdFilePath;
 
    public XmlValidator(String xsdFilePath)
    {
        this.xsdFilePath =xsdFilePath;
    }
 
    public String validata(String xmlFilePath,ErrorHandler errorHandler)
    {
        String msg = null;
        SchemaFactoryfactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try
        {
           Schema schema = factory.newSchema(new File(xsdFilePath));
           Validator validator = schema.newValidator();
           validator.setErrorHandler(errorHandler);
           validator.validate(new StreamSource(new File(xmlFilePath)));
        }
        catch (SAXExceptione)
        {
           msg = e.getMessage();
           e.printStackTrace();
        }
        catch (IOExceptione)
        {
           msg = e.getMessage();
           e.printStackTrace();
        }
        return msg;
    }
 
    public static void main(String[] args)
    {
        String xmlFilePath ="d://test2.xml";
        String xsdFilePath ="d://shiporder.xsd";
        XmlValidator my =new XmlValidator(xsdFilePath);
        String msg =my.validata(xmlFilePath, new DefaultErrorHandler());
       System.out.println(msg == null);
    }
}

如果原XML文件符合Schema文件中的描述则返回true;否则抛出异常进行描述哪里不符合,并且返回false。(具体的操作可在实际工程中自行定制,这里只是进行简单的描述)



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


Statement
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
The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

Building Feeds with XML: A Hands-On Guide to RSSBuilding Feeds with XML: A Hands-On Guide to RSSApr 14, 2025 am 12:17 AM

The steps to build an RSSfeed using XML are as follows: 1. Create the root element and set the version; 2. Add the channel element and its basic information; 3. Add the entry element, including the title, link and description; 4. Convert the XML structure to a string and output it. With these steps, you can create a valid RSSfeed from scratch and enhance its functionality by adding additional elements such as release date and author information.

Creating RSS Documents: A Step-by-Step TutorialCreating RSS Documents: A Step-by-Step TutorialApr 13, 2025 am 12:10 AM

The steps to create an RSS document are as follows: 1. Write in XML format, with the root element, including the elements. 2. Add, etc. elements to describe channel information. 3. Add elements, each representing a content entry, including,,,,,,,,,,,. 4. Optionally add and elements to enrich the content. 5. Ensure the XML format is correct, use online tools to verify, optimize performance and keep content updated.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft