xml 文件正确性验证类实现

很多时候我们的应用程序或者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;

ExpandedBlockStart.gifContractedBlock.gif
/** */ /**
 * 
@author suyuan
 *
 
*/

ExpandedBlockStart.gifContractedBlock.gif
public   class  XmlSchemaValidator  {
    
    
private boolean isValid = true
    
private String xmlErr = "";
    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public boolean isValid() {
        
return isValid;
    }

    
ExpandedSubBlockStart.gifContractedSubBlock.gif    
public String getXmlErr() {
        
return xmlErr;
    }

    
    
public XmlSchemaValidator()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
    }

    
    
    
public boolean ValidXmlDoc(String xml,URL schema)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        StringReader reader 
= new StringReader(xml);
        
return ValidXmlDoc(reader,schema);
    }

    
    
public boolean ValidXmlDoc(Reader xml,URL schema)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try {
            InputStream schemaStream 
= schema.openStream();
            Source xmlSource 
= new StreamSource(xml);
            Source schemaSource 
= new StreamSource(schemaStream);
            
return ValidXmlDoc(xmlSource,schemaSource);
            
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException e) {
            isValid 
= false;
            xmlErr 
= e.getMessage();
            
return false;
        }

    }

    
    
public boolean ValidXmlDoc(String xml,File schema)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        StringReader reader 
= new StringReader(xml);
        
return ValidXmlDoc(reader,schema);
    }

    
    
public boolean ValidXmlDoc(Reader xml,File schema)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try {
            FileInputStream schemaStream 
= new FileInputStream(schema);
            Source xmlSource 
= new StreamSource(xml);
            Source schemaSource 
= new StreamSource(schemaStream);
            
return ValidXmlDoc(xmlSource,schemaSource);
            
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (IOException e) {
            isValid 
= false;
            xmlErr 
= e.getMessage();
            
return false;
        }

    }

    
    
public boolean ValidXmlDoc(Source xml,Source schemaSource)
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
try {              SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);        
            
if(xml==null||xml.equals("")) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{    
                
return false;
            }

            Schema schema 
=  schemafactory.newSchema(schemaSource);
            Validator valid 
=  schema.newValidator();
            valid.validate(xml);
            
return true;
            
ExpandedSubBlockStart.gifContractedSubBlock.gif        }
 catch (SAXException e) {
            isValid 
= false;
            xmlErr 
= e.getMessage();
            
return false;
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
catch (IOException e) {
            isValid 
= false;
            xmlErr 
= e.getMessage();
            
return false;
        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
catch (Exception e) {
            isValid 
= false;
            xmlErr 
= e.getMessage();
            
return false;
        }

    }

}

类的使用方法如下:

package  common.xml.validator;

import  java.io. * ;
import  java.net.URL;


ExpandedBlockStart.gifContractedBlock.gif
public   class  testXmlValidator  {

ExpandedSubBlockStart.gifContractedSubBlock.gif    
/** *//**
     * 
@param args
     
*/

ExpandedSubBlockStart.gifContractedSubBlock.gif    
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
ExpandedBlockStart.gifContractedBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <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
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
private bool isValidXml = true;
        
private string validationError = "";

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Empty Constructor.
        
/// </summary>

        public XmlSchemaValidator()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Public get/set access to the validation error.
        
/// </summary>

        public String ValidationError
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return "<ValidationError>" + this.validationError + "</ValidationError>";
            }

            
set
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.validationError = value;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Public get access to the isValidXml attribute.
        
/// </summary>

        public bool IsValidXml
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return this.isValidXml;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
// The xml does not match the schema.
            isValidXml = false;
            
this.ValidationError = args.Message;
        }
  


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
// Is the xml string valid?
                if(xml == null || xml.Length < 1)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
return false;
                }


                StringReader srXml 
= new StringReader(xml);
                
return ValidXmlDoc(srXml, schemaNamespace, schemaUri);
            }

            
catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.ValidationError = ex.Message;
                
return false;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
// Is the xml object valid?
                if(xml == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    
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)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
this.ValidationError = ex.Message;
                
return false;
            }

        }

    
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
// Continue?
            if(xml == null || schemaNamespace == null || schemaUri == null)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return false;
            }


            isValidXml 
= true;
            XmlValidatingReader vr;
            XmlTextReader tr;
            XmlSchemaCollection schemaCol 
= new XmlSchemaCollection();
            schemaCol.Add(schemaNamespace, schemaUri);

            
try 
ExpandedSubBlockStart.gifContractedSubBlock.gif            

                
// 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)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
{
                    vr.Schemas.Add(schemaCol);
                }

                
// Set the validation event handler.
                vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
                
// Read the xml schema.
                while(vr.Read()) 
ExpandedSubBlockStart.gifContractedSubBlock.gif                

                }
 
                
                vr.Close(); 
                
                
return isValidXml;
            }
 
            
catch(Exception ex) 
ExpandedSubBlockStart.gifContractedSubBlock.gif            

                
this.ValidationError = ex.Message;
                
return false
            }
 
            
finally
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
// Clean up
                vr = null;
                tr 
= null;
            }

        }

    }

}

 


希望 以上类对大家有所帮助,当然我也是在这里做一个标记,以后有需要可以直接用了 呵呵

转载于:https://www.cnblogs.com/suyuan/archive/2008/07/25/1251551.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值