本文整理汇总了C#中System.Xml.XmlValidatingReader类的典型用法代码示例。如果您正苦于以下问题:C# XmlValidatingReader类的具体用法?C# XmlValidatingReader怎么用?C# XmlValidatingReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
XmlValidatingReader类属于System.Xml命名空间,在下文中一共展示了XmlValidatingReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateAndCacheDocument
private XPathDocument CreateAndCacheDocument(XmlReader r, bool supportSchemaDeterminedIDs)
{
string uri = r.BaseURI;
XmlValidatingReader vr = null;
if (supportSchemaDeterminedIDs)
{
vr = new IdAssuredValidatingReader(r);
vr.ValidationType = ValidationType.Auto;
}
else
{
vr = new XmlValidatingReader(r);
vr.ValidationType = ValidationType.None;
}
vr.EntityHandling = EntityHandling.ExpandEntities;
vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(ValidationCallback);
XPathDocument doc = new XPathDocument(vr, XmlSpace.Preserve);
vr.Close();
lock(_cache)
{
if (!_cache.ContainsKey(uri))
_cache.Add(uri, new WeakReference(doc));
}
return doc;
}
示例2: ShouldGenerateASchemaToValidateTestSubClassXml
public void ShouldGenerateASchemaToValidateTestSubClassXml()
{
NetReflectorTypeTable table = new NetReflectorTypeTable
{
typeof (TestClass),
typeof (TestInnerClass),
typeof (TestSubClass)
};
XsdGenerator generator = new XsdGenerator(table);
XmlSchema schema = generator.Generate(true);
#if DEBUG
schema.Write(Console.Out);
#endif
string xmlToValidate = TestClass.GetXmlWithSubClass(DateTime.Today);
#if DEBUG
Console.Out.WriteLine("xmlToValidate = {0}", xmlToValidate);
#endif
XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StringReader(xmlToValidate)));
reader.Schemas.Add(schema);
reader.ValidationType = ValidationType.Schema;
while (reader.Read()) {}
}
示例3: ValidaSchema
/// <summary>
/// Valida se um Xml está seguindo de acordo um Schema
/// </summary>
/// <param name="arquivoXml">Arquivo Xml</param>
/// <param name="arquivoSchema">Arquivo de Schema</param>
/// <returns>True se estiver certo, Erro se estiver errado</returns>
public void ValidaSchema(String arquivoXml, String arquivoSchema)
{
//Seleciona o arquivo de schema de acordo com o schema informado
//arquivoSchema = Bll.Util.ContentFolderSchemaValidacao + "\\" + arquivoSchema;
//Verifica se o arquivo de XML foi encontrado.
if (!File.Exists(arquivoXml))
throw new Exception("Arquivo de XML informado: \"" + arquivoXml + "\" não encontrado.");
//Verifica se o arquivo de schema foi encontrado.
if (!File.Exists(arquivoSchema))
throw new Exception("Arquivo de schema: \"" + arquivoSchema + "\" não encontrado.");
// Cria um novo XMLValidatingReader
var reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(arquivoXml)));
// Cria um schemacollection
var schemaCollection = new XmlSchemaCollection();
//Adiciona o XSD e o namespace
schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", arquivoSchema);
// Adiciona o schema ao ValidatingReader
reader.Schemas.Add(schemaCollection);
//Evento que retorna a mensagem de validacao
reader.ValidationEventHandler += Reader_ValidationEventHandler;
//Percorre o XML
while (reader.Read())
{
}
reader.Close(); //Fecha o arquivo.
//O Resultado é preenchido no reader_ValidationEventHandler
if (validarResultado != "")
{
throw new Exception(validarResultado);
}
}
示例4: ParseItemsConfiguration
public static T_SeamateItems ParseItemsConfiguration(String configPath)
{
TextReader tr = null;
XmlTextReader xml = null;
XmlValidatingReader validate = null;
xml = new XmlTextReader(configPath);
validate = new XmlValidatingReader(xml);
validate.ValidationEventHandler += new ValidationEventHandler(xsdValidationHandler);
while (validate.Read()) { }
validate.Close();
try
{
tr = new StreamReader(configPath);
XmlSerializer serializer = new XmlSerializer(typeof(T_SeamateItems));
T_SeamateItems config = (T_SeamateItems)serializer.Deserialize(tr);
tr.Close();
return config;
}
catch (Exception ex)
{
if (tr != null)
{
tr.Close();
}
throw new Exception("Unable to read configuration file: " + configPath, ex);
}
return null;
}
示例5: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
string xmlFile = Server.MapPath("~/Customers1.xml");
string xsdFile = Server.MapPath("~/Customers.xsd");
XmlTextReader textReader = new XmlTextReader(xmlFile);
XmlValidatingReader validatingReader = new XmlValidatingReader(textReader);
validatingReader.Schemas.Add(null, xsdFile);
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.ValidationEventHandler += new ValidationEventHandler(validatingReader_ValidationEventHandler);
while (validatingReader.Read())
{
if (validatingReader.NodeType == XmlNodeType.Element)
{
if (validatingReader.SchemaType is XmlSchemaComplexType)
{
XmlSchemaComplexType complexType = (XmlSchemaComplexType)validatingReader.SchemaType;
Response.Write(validatingReader.Name + " " + complexType.Name);
}
else
{
object innerText = validatingReader.ReadTypedValue();
Response.Write(validatingReader.Name + " : " + innerText.ToString() + " <br />");
}
}
}
validatingReader.Close();
}
示例6: Validar
/*Validar archivo XML Contra Esquema XSD*/
public void Validar(string rutaFicheroXml)
{
var r = new XmlTextReader(rutaFicheroXml);
var v = new XmlValidatingReader(r) {ValidationType = ValidationType.Schema};
v.ValidationEventHandler += ValidarControlEventos;
var procesarXml = new ConvertirXmlEnTexo();
procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
try
{
while (v.Read())
{
}
// Comprobar si el documento es válido o no.
//return _isValid ? "true" : "false";
// var procesarXml = new ConvertirXmlEnTexo();
// procesarXml.ProcesarArchivo(rutaFicheroXml/*,@"D:\pruebas.txt"*/);
v.Close();
}
catch (Exception e)
{
//ValidarControlEventos(null, null);
// _isValid = false;
// MessageBox.Show("Evento de validación\r\n" + e.Message, @"Validacion de XML",
// MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
////v.ValidationEventHandler += new ValidationEventHandler(ValidarControlEventos);
//return "true";
}
}
示例7: BaseCodeGenerator
public BaseCodeGenerator(Stream sourceXML)
{
XmlDocument doc = new XmlDocument();
using (sourceXML)
{
doc.Load(sourceXML);
}
MemoryStream ms = new MemoryStream();
doc.Save(ms);
ms.Position = 0;
using (XmlTextReader r = new XmlTextReader(ms))
{
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler);
while (v.Read())
{
}
v.Close();
}
if (m_errors)
throw new InvalidDataException("The Xml input did not match the schema");
Parse(doc);
}
示例8: XIncludingReader
/// <summary>
/// Creates new instance of <c>XIncludingReader</c> class with
/// specified underlying <c>XmlReader</c> reader.
/// </summary>
/// <param name="reader">Underlying reader to read from</param>
public XIncludingReader(XmlReader reader)
{
XmlTextReader xtr = reader as XmlTextReader;
if (xtr != null)
{
XmlValidatingReader vr = new XmlValidatingReader(reader);
vr.ValidationType = ValidationType.None;
vr.EntityHandling = EntityHandling.ExpandEntities;
vr.ValidationEventHandler += new ValidationEventHandler(
ValidationCallback);
_normalization = xtr.Normalization;
_whiteSpaceHandling = xtr.WhitespaceHandling;
_reader = vr;
}
else
{
_reader = reader;
}
_nameTable = reader.NameTable;
_keywords = new XIncludeKeywords(NameTable);
if (_reader.BaseURI != "")
_topBaseUri = new Uri(_reader.BaseURI);
else
{
_relativeBaseUri = false;
_topBaseUri = new Uri(Assembly.GetExecutingAssembly().Location);
}
_readers = new Stack<XmlReader>();
_state = XIncludingReaderState.Default;
}
示例9: Read
public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler)
{
WebReferenceOptions options;
XmlValidatingReader reader = new XmlValidatingReader(xmlReader) {
ValidationType = ValidationType.Schema
};
if (validationEventHandler != null)
{
reader.ValidationEventHandler += validationEventHandler;
}
else
{
reader.ValidationEventHandler += new ValidationEventHandler(WebReferenceOptions.SchemaValidationHandler);
}
reader.Schemas.Add(Schema);
webReferenceOptionsSerializer serializer = new webReferenceOptionsSerializer();
try
{
options = (WebReferenceOptions) serializer.Deserialize(reader);
}
catch (Exception exception)
{
throw exception;
}
finally
{
reader.Close();
}
return options;
}
示例10: Main
static void Main (string [] args)
{
string schemaFile = "bug.xsd";
XmlTextReader treader = new XmlTextReader (schemaFile);
XmlSchema sc = XmlSchema.Read (treader, null);
sc.Compile (null);
string page =
"<body xmlns=\"" + sc.TargetNamespace + "\">"
+ "<div>"
+ "</div>"
+ "</body>";
System.Xml.XmlTextReader reader = new XmlTextReader (new StringReader (page));
try {
XmlValidatingReader validator = new System.Xml.XmlValidatingReader (reader);
validator.Schemas.Add (sc);
validator.ValidationType = ValidationType.Schema;
validator.EntityHandling = EntityHandling.ExpandCharEntities;
while (validator.Read ()) {
}
} finally {
reader.Close ();
}
}
示例11: GReader
public GReader(string path)
{
document = new XmlDocument ();
try {
XmlTextReader textreader = new XmlTextReader (path);
XmlValidatingReader vreader = new XmlValidatingReader (textreader);
// Set the validation event handler
vreader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack);
// Load the XML to Document node.
document.Load (textreader);
Console.WriteLine ("Validation finished. Validation {0}", (m_success==true ? "successful!" : "failed."));
//Close the reader.
vreader.Close();
} catch (FileNotFoundException e) {
Console.WriteLine ("Error: {0} not found.", e.FileName);
Environment.Exit (1);
} catch (DirectoryNotFoundException) {
Console.WriteLine ("Error: {0} not found.", path);
Environment.Exit (1);
} catch (XmlException) {
Console.WriteLine ("Error: {0} is not well-formed xml.", path);
Environment.Exit (1);
}
}
示例12: Parse
public static DefaultHighlightingStrategy Parse(SyntaxMode syntaxMode, XmlTextReader xmlTextReader)
{
try {
XmlValidatingReader validatingReader = new XmlValidatingReader(xmlTextReader);
Stream shemaStream = Assembly.GetCallingAssembly().GetManifestResourceStream("Mode.xsd");
validatingReader.Schemas.Add("", new XmlTextReader(shemaStream));
validatingReader.ValidationType = ValidationType.Schema;
validatingReader.ValidationEventHandler += new ValidationEventHandler (ValidationHandler);
XmlDocument doc = new XmlDocument();
doc.Load(validatingReader);
DefaultHighlightingStrategy highlighter = new DefaultHighlightingStrategy(doc.DocumentElement.Attributes["name"].InnerText);
if (doc.DocumentElement.Attributes["extensions"]!= null) {
highlighter.Extensions = doc.DocumentElement.Attributes["extensions"].InnerText.Split(new char[] { ';', '|' });
}
/*
if (doc.DocumentElement.Attributes["indent"]!= null) {
highlighter.DoIndent = Boolean.Parse(doc.DocumentElement.Attributes["indent"].InnerText);
}
*/
XmlElement environment = doc.DocumentElement["Environment"];
highlighter.SetDefaultColor(new HighlightBackground(environment["Default"]));
foreach (string aColorName in environmentColors) {
highlighter.SetColorFor(aColorName, new HighlightColor(environment[aColorName]));
}
// parse properties
if (doc.DocumentElement["Properties"]!= null) {
foreach (XmlElement propertyElement in doc.DocumentElement["Properties"].ChildNodes) {
highlighter.Properties[propertyElement.Attributes["name"].InnerText] = propertyElement.Attributes["value"].InnerText;
}
}
if (doc.DocumentElement["Digits"]!= null) {
highlighter.SetColorFor("Digits", new HighlightColor(doc.DocumentElement["Digits"]));
}
XmlNodeList nodes = doc.DocumentElement.GetElementsByTagName("RuleSet");
foreach (XmlElement element in nodes) {
highlighter.AddRuleSet(new HighlightRuleSet(element));
}
xmlTextReader.Close();
if(errors!=null) {
ReportErrors(syntaxMode.FileName);
errors = null;
return null;
} else {
return highlighter;
}
} catch (Exception) {
//MessageBox.Show("Could not load mode definition file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
return null;
}
}
示例13: ValidateSchema
public static void ValidateSchema(string xml)
{
var schemaStream = typeof(HoptoadValidator).Assembly.GetManifestResourceStream("Tests.hoptoad_2_0.xsd");
var schema = XmlSchema.Read(schemaStream, (sender, args) => { });
var reader = new StringReader(xml);
var xmlReader = new XmlTextReader(reader);
#pragma warning disable 0618
var validator = new XmlValidatingReader(xmlReader);
#pragma warning restore 0618
var errorBuffer = new StringBuilder();
validator.ValidationEventHandler += (sender, args) => {
errorBuffer.AppendLine(args.Message);
};
validator.Schemas.Add(schema);
while (validator.Read())
{
}
if (errorBuffer.ToString().Length > 0)
Assert.Fail(errorBuffer.ToString());
}
示例14: NamespaceMapper
private Hashtable helpNamespaceCache ; // a hashtable to improve lookup speeds
/// <summary>
/// Creates a new instance of the NamespaceMapper class based on the specified map file
/// </summary>
/// <param name="path">Path to the map file</param>
public NamespaceMapper( string path )
{
if ( !schemaIsValid )
throw new Exception( "The namespaceMap schema is not valid or could not be found" );
if ( !File.Exists( path ) )
throw new ArgumentException( string.Format( "{0} could not be found", path ), "path" );
XmlValidatingReader reader = new XmlValidatingReader( new XmlTextReader( path ) );
try
{
reader.Schemas.Add( namespaceMapSchema );
XmlDocument doc = new XmlDocument();
doc.Load( reader );
map = doc.DocumentElement;
Debug.Assert( map != null );
}
finally
{
reader.Close();
}
helpNamespaceCache = new Hashtable();
}
示例15: IsValidXML
/// <summary>
/// Validate XML Format
/// </summary>
/// <param name="text">XML string</param>
public static bool IsValidXML(string text)
{
bool errored;
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(text);
MemoryStream stream = new MemoryStream(byteArray);
XmlTextReader xmlr = new XmlTextReader(stream);
XmlValidatingReader reader = new XmlValidatingReader(xmlr);
try
{
while (reader.Read()) { ; }
errored = false;
}
catch
{
errored = true;
}
finally
{
reader.Close();
}
return !errored;
}