Allan Ebdrup wrote:
Hi
I have two strings in memory, a XML document and a Schema, I would like a
function that takes these two as parameters and returns an errordescriptio n
if the XML does not validate and an empty stirng if the XML does validate
againsg the schema.
What's the easiest way to do this?
Use an XmlValidatingRe ader.
example:
/// <summary>
/// TemplateSetConf igValidator.
/// </summary>
public class TemplateSetConf igValidator
{
#region Class Member Declarations
private string _contentsToVali date;
private ArrayList _errors;
private XmlValidatingRe ader _validator;
private XmlSchemaCollec tion _xsdCollection;
#endregion
/// <summary>
/// CTor
/// </summary>
public TemplateSetConf igValidator(str ing contentsToValid ate)
{
_contentsToVali date = contentsToValid ate;
_errors = new ArrayList();
_xsdCollection = new XmlSchemaCollec tion();
_xsdCollection. Add("http://sd/llblgen/pro/templateSetConf igDefinition.xs d",
Path.Combine(Ap plication.Start upPath,
Constants.Templ ateSetConfigXsd Filename));
}
/// <summary>
/// Validates the set contents if it contains errors. Returns an
arraylist with error informatoin
/// </summary>
/// <returns>true if there are no errors, otherwise false;</returns>
public bool Validate()
{
_errors.Clear() ;
try
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhi tespace=true;
doc.LoadXml(_co ntentsToValidat e);
// try to find <templateSetDef inition> node
XmlNode root = doc.SelectSingl eNode("/templateSetDefi nition");
if(root==null)
{
// not found.
throw new Exception("temp lateSetDefiniti on node not found");
}
XmlAttribute nsAttribute = null;
if(doc.Attribut es!=null)
{
nsAttribute = (XmlAttribute)d oc.Attributes.G etNamedItem("xm lns");
}
if(nsAttribute= =null)
{
nsAttribute = doc.CreateAttri bute("xmlns");
root.Attributes .Append(nsAttri bute);
}
nsAttribute.Val ue = Constants.Templ ateSetConfigTar getNamespace;
_validator = new XmlValidatingRe ader(doc.OuterX ml,
XmlNodeType.Ele ment, null);
_validator.Sche mas.Add(_xsdCol lection);
_validator.Vali dationType = ValidationType. Schema;
_validator.Vali dationEventHand ler+=new
ValidationEvent Handler(validat or_ValidationEv entHandler);
while(_validato r.Read())
{
// optional element examination here;
// The ValidationEvent event is raised whenever an error is encountered
}
}
catch(Exception ex)
{
_errors.Add(new XmlValidationEx ception(ex.Mess age, 1, 1));
}
return (_errors.Count= =0);
}
private void validator_Valid ationEventHandl er(object sender,
ValidationEvent Args e)
{
_errors.Add(new XmlValidationEx ception(e.Excep tion.Message,
e.Exception.Lin eNumber, e.Exception.Lin ePosition));
}
....
Frans
--
------------------------------------------------------------------------
Get LLBLGen Pro, productive O/R mapping for .NET:
http://www.llblgen.com
My .NET blog:
http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------