


Many times our applications or web programs need to use xml files for configuration, and the final program needs to be used by customers, so xml may also need to be written by the customer, and the customer must write it Otherwise, there is no guarantee that the xml file is absolutely correct, so I wrote this class. Its main function is to verify whether the xml written file conforms to the defined xsd specification. The usage of the
package common.xml.validator; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.net.URL; import javax.xml.XMLConstants; import javax.xml.transform.Source; 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.SAXException; /** *//** * @author suyuan * */ public class XmlSchemaValidator { private boolean isValid = true; private String xmlErr = ""; public boolean isValid() { return isValid; } public String getXmlErr() { return xmlErr; } public XmlSchemaValidator() { } public boolean ValidXmlDoc(String xml,URL schema) { StringReader reader = new StringReader(xml); return ValidXmlDoc(reader,schema); } public boolean ValidXmlDoc(Reader xml,URL schema) { try { InputStream schemaStream = schema.openStream(); Source xmlSource = new StreamSource(xml); Source schemaSource = new StreamSource(schemaStream); return ValidXmlDoc(xmlSource,schemaSource); } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } } public boolean ValidXmlDoc(String xml,File schema) { StringReader reader = new StringReader(xml); return ValidXmlDoc(reader,schema); } public boolean ValidXmlDoc(Reader xml,File schema) { try { FileInputStream schemaStream = new FileInputStream(schema); Source xmlSource = new StreamSource(xml); Source schemaSource = new StreamSource(schemaStream); return ValidXmlDoc(xmlSource,schemaSource); } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } } public boolean ValidXmlDoc(Source xml,Source schemaSource) { try { SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); if(xml==null||xml.equals("")) { return false; } Schema schema = schemafactory.newSchema(schemaSource); Validator valid = schema.newValidator(); valid.validate(xml); return true; } catch (SAXException e) { isValid = false; xmlErr = e.getMessage(); return false; } catch (IOException e) { isValid = false; xmlErr = e.getMessage(); return false; } catch (Exception e) { isValid = false; xmlErr = e.getMessage(); return false; } } }
class is as follows:
package common.xml.validator; import java.io.*; import java.net.URL; public class testXmlValidator { /** *//** * @param args */ public static void main(String[] args) { InputStream XmlStream = testXmlValidator.class.getResourceAsStream("test.xml"); Reader XmlReader = new InputStreamReader(XmlStream); URL schema =testXmlValidator.class.getResource("valid.xsd"); XmlSchemaValidator xmlvalid = new XmlSchemaValidator(); System.out.println(xmlvalid.ValidXmlDoc(XmlReader, schema)); System.out.print(xmlvalid.getXmlErr()); } }
xsd file is defined as follows:
<xs:schema id="XSDSchemaTest" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" > <xs:simpleType name="FamilyMemberType"> <xs:restriction base="xs:string"> <xs:enumeration value="384" /> <xs:enumeration value="385" /> <xs:enumeration value="386" /> <xs:enumeration value="" /> </xs:restriction> </xs:simpleType> <xs:element name="Answer"> <xs:complexType> <xs:sequence> <xs:element name="ShortDesc" type="FamilyMemberType" /> <xs:element name="AnswerValue" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
The verified xml instance is as follows:
<?xml version="1.0" encoding="utf-8" ?> <Answer> <ShortDesc>385</ShortDesc> <AnswerValue>1</AnswerValue> </Answer>
This is the java version of the class, and the C# class file is as follows (it is a Written by an old American, my class is translated based on his class):
using System; using System.Xml; using System.Xml.Schema; using System.IO; namespace ProtocolManager.WebApp { /**//// <summary> /// This class validates an xml string or xml document against an xml schema. /// It has public methods that return a boolean value depending on the validation /// of the xml. /// </summary> public class XmlSchemaValidator { private bool isValidXml = true; private string validationError = ""; /**//// <summary> /// Empty Constructor. /// </summary> public XmlSchemaValidator() { } /**//// <summary> /// Public get/set access to the validation error. /// </summary> public String ValidationError { get { return "<ValidationError>" + this.validationError + "</ValidationError>"; } set { this.validationError = value; } } /**//// <summary> /// Public get access to the isValidXml attribute. /// </summary> public bool IsValidXml { get { return this.isValidXml; } } /**//// <summary> /// This method is invoked when the XML does not match /// the XML Schema. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void ValidationCallBack(object sender, ValidationEventArgs args) { // The xml does not match the schema. isValidXml = false; this.ValidationError = args.Message; } /**//// <summary> /// This method validates an xml string against an xml schema. /// </summary> /// <param name="xml">XML string</param> /// <param name="schemaNamespace">XML Schema Namespace</param> /// <param name="schemaUri">XML Schema Uri</param> /// <returns>bool</returns> public bool ValidXmlDoc(string xml, string schemaNamespace, string schemaUri) { try { // Is the xml string valid? if(xml == null || xml.Length < 1) { return false; } StringReader srXml = new StringReader(xml); return ValidXmlDoc(srXml, schemaNamespace, schemaUri); } catch(Exception ex) { this.ValidationError = ex.Message; return false; } } /**//// <summary> /// This method validates an xml document against an xml schema. /// </summary> /// <param name="xml">XmlDocument</param> /// <param name="schemaNamespace">XML Schema Namespace</param> /// <param name="schemaUri">XML Schema Uri</param> /// <returns>bool</returns> public bool ValidXmlDoc(XmlDocument xml, string schemaNamespace, string schemaUri) { try { // Is the xml object valid? if(xml == null) { return false; } // Create a new string writer. StringWriter sw = new StringWriter(); // Set the string writer as the text writer to write to. XmlTextWriter xw = new XmlTextWriter(sw); // Write to the text writer. xml.WriteTo(xw); // Get string strXml = sw.ToString(); StringReader srXml = new StringReader(strXml); return ValidXmlDoc(srXml, schemaNamespace, schemaUri); } catch(Exception ex) { this.ValidationError = ex.Message; return false; } } /**//// <summary> /// This method validates an xml string against an xml schema. /// </summary> /// <param name="xml">StringReader containing xml</param> /// <param name="schemaNamespace">XML Schema Namespace</param> /// <param name="schemaUri">XML Schema Uri</param> /// <returns>bool</returns> public bool ValidXmlDoc(StringReader xml, string schemaNamespace, string schemaUri) { // Continue? if(xml == null || schemaNamespace == null || schemaUri == null) { return false; } isValidXml = true; XmlValidatingReader vr; XmlTextReader tr; XmlSchemaCollection schemaCol = new XmlSchemaCollection(); schemaCol.Add(schemaNamespace, schemaUri); try { // Read the xml. tr = new XmlTextReader(xml); // Create the validator. vr = new XmlValidatingReader(tr); // Set the validation tyep. vr.ValidationType = ValidationType.Auto; // Add the schema. if(schemaCol != null) { vr.Schemas.Add(schemaCol); } // Set the validation event handler. vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Read the xml schema. while(vr.Read()) { } vr.Close(); return isValidXml; } catch(Exception ex) { this.ValidationError = ex.Message; return false; } finally { // Clean up vr = null; tr = null; } } } }
I hope the above class will be helpful to everyone. Of course, I will also make a mark here so that I can use it directly if necessary in the future. hehe
The above is the detailed content of Sample code analysis of xml file correctness verification class. For more information, please follow other related articles on the PHP Chinese website!

RSS2.0 is an open standard that allows content publishers to distribute content in a structured way. It contains rich metadata such as titles, links, descriptions, release dates, etc., allowing subscribers to quickly browse and access content. The advantages of RSS2.0 are its simplicity and scalability. For example, it allows custom elements, which means developers can add additional information based on their needs, such as authors, categories, etc.

RSS is an XML-based format used to publish frequently updated content. 1. RSSfeed organizes information through XML structure, including title, link, description, etc. 2. Creating RSSfeed requires writing in XML structure, adding metadata such as language and release date. 3. Advanced usage can include multimedia files and classified information. 4. Use XML verification tools during debugging to ensure that the required elements exist and are encoded correctly. 5. Optimizing RSSfeed can be achieved by paging, caching and keeping the structure simple. By understanding and applying this knowledge, content can be effectively managed and distributed.

RSS is an XML-based format used to publish and subscribe to content. The XML structure of an RSS file includes a root element, an element, and multiple elements, each representing a content entry. Read and parse RSS files through XML parser, and users can subscribe and get the latest content.

XML has the advantages of structured data, scalability, cross-platform compatibility and parsing verification in RSS. 1) Structured data ensures consistency and reliability of content; 2) Scalability allows the addition of custom tags to suit content needs; 3) Cross-platform compatibility makes it work seamlessly on different devices; 4) Analytical and verification tools ensure the quality and integrity of the feed.

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools
