很多时候我们的应用程序或者web程序需要用到xml文件进行配置,而最终的程序是需要给客户使用的,所以xml或者也需要客户来写,而客户来写的话的,就不能保证xml文件绝对的正确,于是我写了这个类,主要功能就是验证xml书写文件是否符合定义的xsd规范.
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; } } }
类的使用方法如下:
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文件定义如下:
<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>
被验证的xml 实例如下:
<?xml version="1.0" encoding="utf-8" ?> <Answer> <ShortDesc>385</ShortDesc> <AnswerValue>1</AnswerValue> </Answer>
这个是java版本的类,C# 的类文件如下(是一个老美写的,我的类是根据他的类翻译过来的):
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; } } } }
希望 以上类对大家有所帮助,当然我也是在这里做一个标记,以后有需要可以直接用了 呵呵
以上是xml文件正确性验证类的示例代码分析的详细内容。更多信息请关注PHP中文网其他相关文章!

rssfeedsarexmldocuments usedforcontentAggregation and distribution.totransformthemintoreadableContent:1)parsethethexmlusinglibrarieslibrariesliblarieslikeparserinparserinpython.2)andledifferentifferentrssssssssssssssssssssssssssssssssssssssssssssssersions andpotentionparsingrorS.3)

JSONFeed是一种基于JSON的RSS替代方案,其优势在于简洁性和易用性。1)JSONFeed使用JSON格式,易于生成和解析。2)它支持动态生成,适用于现代Web开发。3)使用JSONFeed可以提升内容管理效率和用户体验。

如何构建、验证和发布RSSfeeds?1.构建:使用Python脚本生成RSSfeed,包含标题、链接、描述和发布日期。2.验证:使用FeedValidator.org或Python脚本检查RSSfeed是否符合RSS2.0标准。3.发布:将RSS文件上传到服务器,或使用Flask动态生成并发布RSSfeed。通过这些步骤,你可以有效管理和分享内容。

确保XML/RSSfeeds安全性的方法包括:1.数据验证,2.加密传输,3.访问控制,4.日志和监控。这些措施通过网络安全协议、数据加密算法和访问控制机制来保护数据的完整性和机密性。

XML是一种标记语言,用于存储和传输数据,RSS是一种基于XML的格式,用于发布频繁更新的内容。1)XML通过标签和属性描述数据结构,2)RSS定义特定标签发布和订阅内容,3)使用Python的xml.etree.ElementTree模块可以创建和解析XML,4)XPath表达式可查询XML节点,5)feedparser库可解析RSSfeed,6)常见错误包括标签不匹配和编码问题,可用xmllint验证,7)使用SAX解析器处理大型XML文件可优化性能。

XML是一种用于数据存储和交换的标记语言,RSS是基于XML的格式,用于发布更新内容。1.XML定义数据结构,适合数据交换和存储。2.RSS用于内容订阅,解析时使用专门库。3.解析XML可使用DOM或SAX,生成XML和RSS需正确设置元素和属性。

使用Python可以从XML/RSS转换到JSON。1)解析源数据,2)提取字段,3)转换为JSON,4)输出JSON。使用xml.etree.ElementTree和feedparser库解析XML/RSS,使用json库生成JSON数据。

XML/RSS和RESTAPI在现代网络开发中协同工作,通过以下方式:1)XML/RSS用于内容发布和订阅,2)RESTAPI用于设计和操作网络服务。结合使用这两者可以实现高效的内容管理和动态更新。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

Atom编辑器mac版下载
最流行的的开源编辑器

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3汉化版
中文版,非常好用