问题
I am new to XSD world, I worked with XML but not much programtically. I have successfully generated C# classes using XSD2Code.Can somebody please guide me how can I use those generated classes using C# and use my XML to get validated.
Code snippet would be hightly appreciated.
Thanks and regards.
回答1:
Validating an XML does not need to have the generated classes. Lets see this helper class:
public class Validator
{
XmlSchemaSet schemaset;
ILog logger;
static Validator instance;
static object lockObject = new Object();
public static Validator Instance
{
get { return instance; }
}
public Validator(string schemaPath)
{
WarningAsErrors = true;
logger = LogManager.GetLogger(GetType().Name);
schemaset = new XmlSchemaSet();
foreach (string s in Directory.GetFiles(schemaPath, "*.xsd"))
{
schemaset.Add(XmlSchema.Read(XmlReader.Create(s),new ValidationEventHandler((ss,e)=>OnValidateReadSchema(ss,e))));
}
instance = this;
}
private void OnValidateReadSchema(object ss, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error)
logger.Error(e.Message);
else
logger.Warn(e.Message);
}
public bool WarningAsErrors { get; set; }
private string FormatLineInfo(XmlSchemaException xmlSchemaException)
{
return string.Format(" Line:{0} Position:{1}", xmlSchemaException.LineNumber, xmlSchemaException.LinePosition);
}
protected void OnValidate(object _, ValidationEventArgs vae)
{
if (vae.Severity == XmlSeverityType.Error)
logger.Error(vae.Message);
else
logger.Warn(vae.Message);
if (vae.Severity == XmlSeverityType.Error || WarningAsErrors)
errors.AppendLine(vae.Message + FormatLineInfo(vae.Exception));
else
warnings.AppendLine(vae.Message + FormatLineInfo(vae.Exception));
}
public string ErrorMessage { get; set; }
public string WarningMessage { get; set; }
StringBuilder errors, warnings;
public void Validate(String doc)
{
lock (lockObject)
{
errors = new StringBuilder();
warnings = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += new ValidationEventHandler((o, e) => OnValidate(o, e)); // Your callback...
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(schemaset);
settings.ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;
// Wrap document in an XmlNodeReader and run validation on top of that
try
{
using (XmlReader validatingReader = XmlReader.Create(new StringReader(doc), settings))
{
while (validatingReader.Read()) { /* just loop through document */ }
}
}
catch (XmlException e)
{
errors.AppendLine(string.Format("Error at line:{0} Posizione:{1}", e.LineNumber, e.LinePosition));
}
ErrorMessage = errors.ToString();
WarningMessage = warnings.ToString();
}
}
}
In order to use it, just create an instance of Validator
, passing the path where your xsd stays. Then call Validate(string) passing the XML document content. You will find the ErrorMessage
and WarningMessage
properties set up with the errors/warning found ( if one ). In order to work, the XML document has to have the proper(s) xmlns
declared. Notice my class uses log4net by default as a logger mechanism, so it will not compile as is unless you are using log4net too.
回答2:
Looking at the generated Serialize and Deserialize methods of Xsd2Code, it doesn't look like it does schema validation. I haven't used Xsd2Code much, so I might be wrong.
But what you could do is use the XmlReaderSettings class to set up the schemas the XML will use.
// Load the Schema Into Memory. The Error handler is also presented here.
StringReader sr = new StringReader(File.ReadAllText("schemafile.xsd"));
XmlSchema sch = XmlSchema.Read(sr,SchemaErrorsHandler);
// Create the Reader settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(sch);
// Create an XmlReader specifying the settings.
StringReader xmlData = new StringReader(File.ReadAllText("xmlfile.xml"));
XmlReader xr = XmlReader.Create(xmlData,settings);
// Use the Native .NET Serializer (probably u cud substitute the Xsd2Code serializer here.
XmlSerializer xs = new XmlSerializer(typeof(SerializableClass));
var data = xs.Deserialize(xr);
来源:https://stackoverflow.com/questions/6451519/how-to-use-xsd2code-generated-c-sharp-classes