SchemeNode CreateSchemeNode(XmlTextReader reader, bool userList) { try { XmlValidatingReader validatingReader = new XmlValidatingReader(reader); Stream schemaStream = typeof(SyntaxMode).Assembly.GetManifestResourceStream("Mode.xsd"); validatingReader.Schemas.Add("", new XmlTextReader(schemaStream)); validatingReader.ValidationType = ValidationType.Schema; validatingReader.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); XmlDocument doc = new XmlDocument(); doc.Load(validatingReader); if (errors.Count != 0) { ReportErrors(); validatingReader.Close(); return(null); } else { validatingReader.Close(); return(new SchemeNode(doc.DocumentElement, userList)); } } catch (Exception e) { MessageService.ShowError(e, "${res:Dialog.Options.TextEditorOptions.EditHighlighting.LoadError}"); return(null); } finally { reader.Close(); } }
private object getShiolEvents(string strDate) { List <DataFrameStructure> objs = new List <DataFrameStructure>(); XmlValidatingReader vr = null; try { DateTime date = DateTime.ParseExact(strDate.Replace("-", ""), "yyyyMMdd", CultureInfo.InvariantCulture); //DateTime date = DateTime.Today; // DateTime.ParseExact("20180130", "yyyyMMdd", CultureInfo.InvariantCulture); //string fullPathToFile = Path.Combine(dir, fileName); string file = "-" + date.ToString("yyyy-MM-dd"); createHeaderFile("Tramas" + file); vr = new XmlValidatingReader(new XmlTextReader(Path.Combine(ShiolConfiguration.Instance.Config.LogDirectory, "Tramas" + file + ".xml"))); vr.ValidationType = ValidationType.None; vr.EntityHandling = EntityHandling.ExpandEntities; XmlDocument doc = new XmlDocument(); doc.Load(vr); foreach (XmlElement element in doc.SelectNodes("//Event")) { var Processed = element.LastChild; var Received = element.FirstChild; //DataFrameStructure uFrameProvider = XmlConvert.DeserializeObject<DataFrameStructure>(Processed.InnerXml); DataFrameStructure obj = new DataFrameStructure() { Date = Processed["Date"].InnerText, Time = Processed["Time"].InnerText, UserID = Processed["UserID"].InnerText, DialedNumber = Processed["DialedNumber"].InnerText, Duration = Processed["Duration"].InnerText, Anexo = Processed["Anexo"].InnerText, Shiol = Processed["Shiol"] != null ? Processed["Shiol"].InnerText : "" }; objs.Add(obj); } vr.Close(); deleteHeaderFile("Tramas" + file); } catch { if (vr != null) { vr.Close(); } } return(objs); }
public void Validate() { try { // Схема XmlTextReader schemaReader = new XmlTextReader(xsdFileName); XmlSchemaCollection schema = new XmlSchemaCollection(); schema.Add(null, schemaReader); // Валидатор XmlTextReader xmlReader = new XmlTextReader(xmlFileName); XmlValidatingReader vr = new XmlValidatingReader(xmlReader); vr.Schemas.Add(schema); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); // Валидация while (vr.Read()) { ; } vr.Close(); } catch (Exception e) { errorMessage += e.Message + "\r\n"; } }
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); }
static int Main () { XmlSchema schema = XmlSchema.Read (new XmlTextReader ("schema.xsd"), null); #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add (schema); XmlReader reader = XmlReader.Create (new StringReader (xml), settings); try { while (reader.Read ()) ; return 1; } catch (XmlSchemaValidationException) { } finally { reader.Close (); } #endif XmlValidatingReader validator = new XmlValidatingReader (xml, XmlNodeType.Document, null); validator.ValidationType = ValidationType.Schema; validator.Schemas.Add (schema); try { while (validator.Read ()) ; return 2; } catch (XmlSchemaException) { } finally { validator.Close (); } return 0; }
/// <summary> /// validates xml file against embedded schema file /// </summary> /// <param name="filename"></param> private void ValidateSchema(String filename) { try { ResourceManager rm = new ResourceManager(); ValidationEventHandler veh = new ValidationEventHandler(SchemaValidationEventHandler); XmlSchema xsd = XmlSchema.Read(rm.ConfigSchema, veh); XmlTextReader xml = XIncludeReader.GetXmlTextReader(filename); XmlValidatingReader vr = new XmlValidatingReader(xml); vr.Schemas.Add(xsd); vr.ValidationType = ValidationType.Schema; // and validation errors events go to... vr.ValidationEventHandler += veh; // wait until the read is over, its occuring in a different thread - kinda like // when your walking to get a cup of coffee and your mind is in Hawaii while (vr.Read()) { ; } vr.Close(); } catch (UnauthorizedAccessException ex) { //dont have access permission IsValid = false; WriteToLog(ParserValidationMessage.NewError(ex.Message).ToString()); } catch (Exception ex) { //and other things that could go wrong IsValid = false; WriteToLog(ParserValidationMessage.NewError(ex.Message).ToString()); } }
public static void Main() { //Create the validating reader. XmlTextReader txtreader = new XmlTextReader("book1.xml"); txtreader.WhitespaceHandling = WhitespaceHandling.None; XmlValidatingReader reader = new XmlValidatingReader(txtreader); reader.ValidationType = ValidationType.None; //Parse the file and each node and its value. while (reader.Read()) { if (reader.HasValue) { Console.WriteLine("({0}) {1}={2}", reader.NodeType, reader.Name, reader.Value); } else { Console.WriteLine("({0}) {1}", reader.NodeType, reader.Name); } } //Close the reader. reader.Close(); }
private void Validate(String filename, XmlSchemaCollection xsc) { m_success = true; Console.WriteLine(); Console.WriteLine("Validating XML file {0}...", filename.ToString()); reader = new XmlTextReader(filename); //Create a validating reader. vreader = new XmlValidatingReader(reader); //Validate using the schemas stored in the schema collection. vreader.Schemas.Add(xsc); //Set the validation event handler vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); //Read and validate the XML data. while (vreader.Read()) { } Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful" : "failed")); Console.WriteLine(); //Close the reader. vreader.Close(); }
/// <include file='doc\WebReferenceOptions.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static WebReferenceOptions Read(XmlReader xmlReader, ValidationEventHandler validationEventHandler) { XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); validatingReader.ValidationType = ValidationType.Schema; if (validationEventHandler != null) { validatingReader.ValidationEventHandler += validationEventHandler; } else { validatingReader.ValidationEventHandler += new ValidationEventHandler(SchemaValidationHandler); } validatingReader.Schemas.Add(Schema); webReferenceOptionsSerializer ser = new webReferenceOptionsSerializer(); try { return((WebReferenceOptions)ser.Deserialize(validatingReader)); } catch (Exception e) { throw e; } finally { validatingReader.Close(); } }
public static void Main(string[] args) { if (args.Length == 0 || args.Length != 1) { System.Console.WriteLine("Usage: XSDValidator.exe <xml file>\nEnsure that the xsd is in the same folder as xml file."); return; } string xmlFileName = args[0]; XmlTextReader r = new XmlTextReader(xmlFileName); XmlValidatingReader v = new XmlValidatingReader(r); v.ValidationType = ValidationType.Schema; v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler); while (v.Read()) { } v.Close(); if (!isValid) { System.Console.WriteLine("Xml document is not valid."); } else { System.Console.WriteLine("Xml Document is valid."); } }
private bool IsValidXml(string message) { if (Regex.Match(message, @"^<.*>").Success) { XmlNodeType type = XmlNodeType.Element; // if we have an xml decl then parse as a document node type // works around mono incompatibility bug #61274 if (Regex.Match(message, @"^<\?xml\sversion.*\?>").Success) { type = XmlNodeType.Document; } // validate xml XmlValidatingReader reader = new XmlValidatingReader(message, type, null); try { while (reader.Read()) { } } catch { return(false); } finally { reader.Close(); } return(true); } return(false); }
public bool Validate() { success = true; try { // Set the validation event handler myXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle); // Read XML data while (myXmlValidatingReader.Read()) { } } catch (Exception e) { throw new NUnitException(e.Message, e); } finally { myXmlValidatingReader.Close(); } return(success); }
public static void Main() { XmlValidatingReader reader = null; XmlTextReader txtreader = null; try { //Create the validating reader. txtreader = new XmlTextReader("http://localhost/uri.xml"); reader = new XmlValidatingReader(txtreader); reader.ValidationType = ValidationType.None; //Parse the file and display the base URI for each node. while (reader.Read()) { Console.WriteLine("({0}) {1}", reader.NodeType, reader.BaseURI); } } finally { if (reader != null) { reader.Close(); } } }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Syntax; VALIDATE xmldoc schemadoc"); return; } XmlValidatingReader reader = null; try { XmlTextReader nvr = new XmlTextReader(args[0]); nvr.WhitespaceHandling = WhitespaceHandling.None; reader = new XmlValidatingReader(nvr); reader.Schemas.Add(GetTargetNamespace(args[1]), args[1]); reader.ValidationEventHandler += new ValidationEventHandler(OnValidationError); while (reader.Read()) { ; } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (reader != null) { reader.Close(); } } }
private string Validate(ValidationType validationType) { if (validationType != ValidationType.DTD && validationType != ValidationType.Schema) { throw new ArgumentException(); } StringBuilder xmlValMsg = new StringBuilder(); XmlTextReader reader = new XmlTextReader(_databasePath); XmlValidatingReader validator = new XmlValidatingReader(reader); validator.ValidationType = validationType; if (validationType == ValidationType.Schema) { validator.Schemas.Add(null, _xsdFilePath); } validator.ValidationEventHandler += new ValidationEventHandler(delegate(object sender, ValidationEventArgs args) { xmlValMsg.AppendLine(args.Message); }); while (validator.Read()) { ; } string result = xmlValMsg.ToString(); if (string.IsNullOrEmpty(result)) { result = "Plik XML jest poprawny z " + validationType; } validator.Close(); return(result); }
public static void Main() { XmlTextReader txtreader = null; XmlValidatingReader reader = null; try { //Implement the readers. txtreader = new XmlTextReader("elems.xml"); reader = new XmlValidatingReader(txtreader); //Parse the XML and display the text content of each of the elements. while (reader.Read()){ if (reader.IsStartElement()){ if (reader.IsEmptyElement) Console.WriteLine("<{0}/>", reader.Name); else{ Console.Write("<{0}> ", reader.Name); reader.Read(); //Read the start tag. if (reader.IsStartElement()) //Handle nested elements. Console.Write("\r\n<{0}>", reader.Name); Console.WriteLine(reader.ReadString()); //Read the text content of the element. } } } } finally { if (reader != null) reader.Close(); } }
public bool xmlValidatorFromDTD(string xmlPath) { //creazione del doc con trattamento spazi bianchi XmlDocument doc = new XmlDocument(); BusinessLogic.Interoperabilità.InteropResolver my = new BusinessLogic.Interoperabilità.InteropResolver(); XmlTextReader xtr = new XmlTextReader(xmlPath); xtr.WhitespaceHandling = WhitespaceHandling.None; XmlValidatingReader xvr = new XmlValidatingReader(xtr); xvr.ValidationType = System.Xml.ValidationType.DTD; xvr.EntityHandling = System.Xml.EntityHandling.ExpandCharEntities; xvr.XmlResolver = my; bool esito = true; try { doc.Load(xvr); } catch (System.Xml.Schema.XmlSchemaException e) { logger.Debug("Errore nella validazione del file segnatura.XML: Eccezione:" + e.Message); esito = false; } finally { xvr.Close(); xtr.Close(); } return(esito); }
static void Main (string[] args) { if (args.Length < 2) { Console.WriteLine("Syntax; VALIDATE xmldoc schemadoc"); return; } XmlValidatingReader reader = null; try { XmlTextReader nvr = new XmlTextReader (args[0]); nvr.WhitespaceHandling = WhitespaceHandling.None; reader = new XmlValidatingReader (nvr); reader.Schemas.Add (GetTargetNamespace (args[1]), args[1]); reader.ValidationEventHandler += new ValidationEventHandler(OnValidationError); while (reader.Read ()); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (reader != null) reader.Close(); } }
static void Main(string[] args) { // Create a cache of schemas, and add two schemas XmlSchemaCollection sc = new XmlSchemaCollection(); sc.Add("urn:MyUri", "../../../doctors.xsd"); //sc.Add("", "../../../doctors.xsd"); // Create a validating reader object XmlTextReader tr = new XmlTextReader("../../../doctors.xml"); XmlValidatingReader vr = new XmlValidatingReader(tr); // Specify the type of validation required vr.ValidationType = ValidationType.Schema; // Tell the validating reader to use the schema collection vr.Schemas.Add(sc); // Register a validation event handler method vr.ValidationEventHandler += new ValidationEventHandler(MyHandler); // Read and validate the XML document try { int num = 0; float avg_age = 0; while (vr.Read()) { if (vr.NodeType == XmlNodeType.Element && vr.LocalName == "P") { num++; vr.MoveToFirstAttribute(); Console.WriteLine(vr.Value); vr.MoveToNextAttribute(); vr.MoveToNextAttribute(); string val = vr.Value; if (val != "male" && val != "female") { //Console.WriteLine(val); avg_age += Convert.ToInt32(vr.Value); } vr.MoveToElement(); } } Console.WriteLine("Number of Passengers: " + num + "\n"); Console.WriteLine("Average age: " + avg_age / num + "\n"); } catch (XmlException ex) { Console.WriteLine("XMLException occurred: " + ex.Message); } finally { vr.Close(); } }
private void Validate(String filename) { try { Console.WriteLine("Validating XML file " + filename.ToString()); txtreader = new XmlTextReader(filename); reader = new XmlValidatingReader(txtreader); // Set the validation event handler reader.ValidationEventHandler += new ValidationEventHandler(this.ValidationEventHandle); // Read XML data while (reader.Read()) { } Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful" : "failed")); } finally { //Close the reader. if (reader != null) { reader.Close(); } } }
/// <summary> /// Validates of xml file with Schema. /// </summary> /// <param name="arg0">args[0] - argument of cmd</param> /// <param name="arg1">args[1] - argument of cmd</param> private static void ValidateXMLFile(string arg0, string arg1) { XmlValidatingReader validateReader = null; XmlTextReader nvr = null; try { nvr = new XmlTextReader(arg0); nvr.WhitespaceHandling = WhitespaceHandling.None; validateReader = new XmlValidatingReader(nvr); validateReader.Schemas.Add(GetTargetNamespace(arg1), arg1); validateReader.ValidationEventHandler += new ValidationEventHandler(OnValidationError); while (validateReader.Read()) { ; } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (validateReader != null) { validateReader.Close(); } } }
private bool IsValidXml(string message) { if (Regex.Match(message, @"^<.*>").Success) { XmlValidatingReader reader = null; try { // validate xml reader = new XmlValidatingReader(message, XmlNodeType.Document, null); while (reader.Read()) { } // the xml is valid return(true); } catch { return(false); } finally { if (reader != null) { reader.Close(); } } } return(false); }
public void PushInputDocument(string url) { Uri baseUri = (!(this.Input.BaseURI == string.Empty)) ? new Uri(this.Input.BaseURI) : null; Uri uri = this.res.ResolveUri(baseUri, url); string url2 = (!(uri != null)) ? string.Empty : uri.ToString(); using (Stream stream = (Stream)this.res.GetEntity(uri, null, typeof(Stream))) { if (stream == null) { throw new XsltCompileException("Can not access URI " + uri.ToString(), null, this.Input); } XmlValidatingReader xmlValidatingReader = new XmlValidatingReader(new XmlTextReader(url2, stream, this.nsMgr.NameTable)); xmlValidatingReader.ValidationType = ValidationType.None; XPathNavigator xpathNavigator = new XPathDocument(xmlValidatingReader, XmlSpace.Preserve).CreateNavigator(); xmlValidatingReader.Close(); xpathNavigator.MoveToFirstChild(); while (xpathNavigator.NodeType != XPathNodeType.Element) { if (!xpathNavigator.MoveToNext()) { IL_F9: this.PushInputDocument(xpathNavigator); return; } } goto IL_F9; } }
public void CopyXmlFile(String inputFilePath, String outputFilePath) { if (this.Verbose) { Log(Level.Info, string.Format("Copying {0} to {1}.", inputFilePath, outputFilePath)); } XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(inputFilePath)); XmlTextWriter writer = new XmlTextWriter(outputFilePath, Encoding.UTF8); reader.ValidationType = ValidationType.None; reader.EntityHandling = EntityHandling.ExpandEntities; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.DocumentType: break; case XmlNodeType.Whitespace: break; default: writer.WriteNode(reader, true); break; } } writer.Close(); reader.Close(); }
/// <summary> /// Validate XML Format /// </summary> /// <param name="text">XML string</param> public static bool IsValidXML(string text) { if (text == null) { return(false); } 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); }
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); }
/* Takes a type name, and a valid example of that type, * Creates a schema consisting of a single element of that * type, and validates a bit of xml containing the valid * value, with whitespace against that schema. * * FIXME: Really we want to test the value of whitespace more * directly that by creating a schema then parsing a string. * */ public void WhiteSpaceTest(string type, string valid) { passed = true; XmlSchema schema = new XmlSchema(); schema.TargetNamespace = "http://example.com/testCase"; XmlSchemaElement element = new XmlSchemaElement(); element.Name = "a"; element.SchemaTypeName = new XmlQualifiedName(type, "http://www.w3.org/2001/XMLSchema"); schema.Items.Add(element); schema.Compile(new ValidationEventHandler(ValidationCallbackOne)); XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(new StringReader("<a xmlns='http://example.com/testCase'>\n\n" + valid + "\n\n</a>"))); vr.Schemas.Add(schema); vr.ValidationType = ValidationType.Schema; // vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne); while (vr.Read()) { } ; vr.Close(); Assert.IsTrue(passed, type + " doesn't collapse whitespace: " + (errorInfo != null ? errorInfo.Message : null)); }
private static bool validateXml(String infile) { //First we create the xmltextreader XmlTextReader xmlr = new XmlTextReader(infile); //We pass the xmltextreader into the xmlvalidatingreader //This will validate the xml doc with the schema file //NOTE the xml file it self points to the schema file XmlValidatingReader xmlvread = new XmlValidatingReader(xmlr); // Set the validation event handler xmlvread.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); m_Success = true; //make sure to reset the success var // Read XML data while (xmlvread.Read()) { } //Close the reader. xmlvread.Close(); //The validationeventhandler is the only thing that would set //m_Success to false return(m_Success); }
public static Tuple <bool, string> ValidateAgainstSchema(string xmlPath, string schemaPath) { bool result = true; string resultMessage = ""; FileStream stream = new FileStream(xmlPath, FileMode.Open); XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null); vr.Schemas.Add(null, schemaPath); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += (sender, args) => { result = false; resultMessage += args.Message + '\n'; }; try { while (vr.Read()) { } } catch (Exception e) { resultMessage += e.Message + '\n'; } finally { vr.Close(); stream.Close(); } return(new Tuple <bool, string>(result, resultMessage)); }
public void PushInputDocument(string url) { // todo: detect recursion Uri baseUriObj = (Input.BaseURI == String.Empty) ? null : new Uri(Input.BaseURI); Uri absUri = res.ResolveUri(baseUriObj, url); string absUriString = absUri != null?absUri.ToString() : String.Empty; using (Stream s = (Stream)res.GetEntity(absUri, null, typeof(Stream))) { if (s == null) { throw new XsltCompileException("Can not access URI " + absUri.ToString(), null, Input); } XmlValidatingReader vr = new XmlValidatingReader(new XmlTextReader(absUriString, s, nsMgr.NameTable)); vr.ValidationType = ValidationType.None; XPathNavigator n = new XPathDocument(vr, XmlSpace.Preserve).CreateNavigator(); vr.Close(); n.MoveToFirstChild(); do { if (n.NodeType == XPathNodeType.Element) { break; } }while (n.MoveToNext()); PushInputDocument(n); } }
private void LoadDataFromXML(string Filename) { try { FileInfo XMLInfo = new FileInfo(Filename); string XMLName = XMLInfo.Name.Substring(0, XMLInfo.Name.Length - XMLInfo.Extension.Length); XmlValidatingReader XMLReader = new XmlValidatingReader(File.OpenRead(Filename), XmlNodeType.Element, null); XMLReader.ValidationType = ValidationType.None; //Load the schema from the global resource stream... Stream XMLSchema = Utilities.GetStreamResource("Resources." + XMLName + ".xsd"); if (XMLSchema != null) { XmlTextReader XMLSchemaReader = new XmlTextReader(XMLSchema); XMLReader.Schemas.Add("", XMLSchemaReader); XMLReader.ValidationType = ValidationType.Schema; XMLSchema.Position = 0; m_Data.ReadXmlSchema(XMLSchema); } m_Data.ReadXml(XMLReader); ConvertNumericFields(); XMLReader.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } }
public static void Main() { XmlTextReader txtreader = null; XmlValidatingReader reader = null; try { //Load the reader with the data file and ignore all white space nodes. txtreader = new XmlTextReader(filename); txtreader.WhitespaceHandling = WhitespaceHandling.None; //Implement the validating reader over the text reader. reader = new XmlValidatingReader(txtreader); reader.ValidationType = ValidationType.None; //Parse the file and display each of the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("<{0}>", reader.Name); break; case XmlNodeType.Text: Console.Write(reader.Value); break; case XmlNodeType.CDATA: Console.Write("<![CDATA[{0}]]>", reader.Value); break; case XmlNodeType.ProcessingInstruction: Console.Write("<?{0} {1}?>", reader.Name, reader.Value); break; case XmlNodeType.Comment: Console.Write("<!--{0}-->", reader.Value); break; case XmlNodeType.XmlDeclaration: Console.Write("<?xml version='1.0'?>"); break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: Console.Write("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value); break; case XmlNodeType.EntityReference: Console.Write(reader.Name); break; case XmlNodeType.EndElement: Console.Write("</{0}>", reader.Name); break; } } } finally { if (reader!=null) reader.Close(); } }
protected void cmdValidate_Click(object sender, EventArgs e) { string filePath = ""; if (optValid.Checked) { filePath = Server.MapPath("DvdList.xml"); } else if (optInvalidData.Checked) { filePath += Server.MapPath("DvdListInvalid.xml"); } lblStatus.Text = ""; // Open the XML file. FileStream fs = new FileStream(filePath, FileMode.Open); XmlTextReader r = new XmlTextReader(fs); // Create the validating reader. XmlValidatingReader vr = new XmlValidatingReader(r); vr.ValidationType = ValidationType.Schema; // Add the XSD file to the validator. XmlSchemaCollection schemas = new XmlSchemaCollection(); schemas.Add("", Server.MapPath("DvdList.xsd")); vr.Schemas.Add(schemas); // Connect the event handler. vr.ValidationEventHandler += new ValidationEventHandler(MyValidateHandler); // Read through the document. while (vr.Read()) { // Process document here. // If an error is found, an exception will be thrown. } vr.Close(); lblStatus.Text += "<br>Complete."; }
static int Main () { XmlSchema schema = XmlSchema.Read (new XmlTextReader ("schema.xsd"), null); #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.None; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(schema); XmlReader reader = XmlReader.Create (new StringReader (xml), settings); XmlNamespaceManager manager = new XmlNamespaceManager (reader.NameTable); XmlSchemaValidator validator = new XmlSchemaValidator (reader.NameTable, schemaSet, manager, XmlSchemaValidationFlags.None); validator.Initialize (); validator.ValidateElement ("test", string.Empty, null); try { validator.ValidateAttribute ("mode", string.Empty, "NOT A ENUMERATION VALUE", null); return 1; } catch (XmlSchemaValidationException) { } finally { reader.Close (); } #else XmlValidatingReader validator = new XmlValidatingReader (xml, XmlNodeType.Document, null); validator.ValidationType = ValidationType.Schema; validator.Schemas.Add (schema); try { while (validator.Read ()) ; return 1; } catch (XmlSchemaException) { } finally { validator.Close (); } #endif return 0; }
private static bool ValidateWithXSD(XmlReader reader) { XmlValidatingReader valReader; XmlSchema schema; Stream xsdStream; val_success = true; valReader = new XmlValidatingReader (reader); valReader.ValidationType = ValidationType.Schema; // Set the validation event handler valReader.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); xsdStream = Assembly.GetExecutingAssembly ().GetManifestResourceStream ("style.xsd"); schema = XmlSchema.Read (xsdStream, null); schema.Compile (null); valReader.Schemas.Add (schema); while (valReader.Read()){} valReader.Close(); return val_success; }
private void Init( XmlReader reader ) { XmlValidatingReader vr = null; try { vr = new XmlValidatingReader( reader ); vr.EntityHandling = EntityHandling.ExpandEntities; vr.ValidationType = ValidationType.None; vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); Load( vr ); } finally { vr.Close(); reader.Close(); } }
private bool LoadSchema(string uri, string url) { bool expectXdr = false; uri = nameTable.Add(uri); if (SchemaInfo.HasSchema(uri)) { return false; } SchemaInfo schemaInfo = null; if (schemaCollection != null) schemaInfo = schemaCollection.GetSchemaInfo(uri); if (schemaInfo != null) { /* if (SkipProcess(schemaInfo.SchemaType)) return false; */ if (!IsCorrectSchemaType(schemaInfo.SchemaType)) { throw new XmlException(Res.Xml_MultipleValidaitonTypes, string.Empty, this.positionInfo.LineNumber, this.positionInfo.LinePosition); } SchemaInfo.Add(uri, schemaInfo, validationEventHandler); return true; } if (this.xmlResolver == null) return false; if (url == null && IsXdrSchema(uri)) { /* */ if (ValidationFlag != ValidationType.XDR && ValidationFlag != ValidationType.Auto) { return false; } url = uri.Substring(x_schema.Length); expectXdr = true; } if (url == null) { return false; } XmlSchema schema = null; XmlReader reader = null; try { Uri ruri = this.xmlResolver.ResolveUri(baseUri, url); Stream stm = (Stream)this.xmlResolver.GetEntity(ruri,null,null); reader = new XmlTextReader(ruri.ToString(), stm, nameTable); schemaInfo = new SchemaInfo(schemaNames); Parser sparser = new Parser(schemaCollection, nameTable, schemaNames, validationEventHandler); schema = sparser.Parse(reader, uri, schemaInfo); while(reader.Read());// wellformness check } catch(XmlSchemaException e) { SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {uri, e.Message}, XmlSeverityType.Error); schemaInfo = null; } catch(Exception e) { SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {uri, e.Message}, XmlSeverityType.Warning); schemaInfo = null; } finally { if (reader != null) { reader.Close(); } } if (schemaInfo != null) { int errorCount = 0; if (schema != null) { if (expectXdr) { throw new XmlException(Res.Sch_XSCHEMA, string.Empty, this.positionInfo.LineNumber, this.positionInfo.LinePosition); } if (schema.ErrorCount == 0) { schema.Compile(schemaCollection, nameTable, schemaNames, validationEventHandler, uri, schemaInfo, true); } errorCount += schema.ErrorCount; } else { errorCount += schemaInfo.ErrorCount; } if (errorCount == 0) { if (SkipProcess(schemaInfo.SchemaType)) return false; if (!IsCorrectSchemaType(schemaInfo.SchemaType)) { throw new XmlException(Res.Xml_MultipleValidaitonTypes, string.Empty, this.positionInfo.LineNumber, this.positionInfo.LinePosition); } SchemaInfo.Add(uri, schemaInfo, validationEventHandler); schemaCollection.Add(uri, schemaInfo, schema, false); return true; } } return false; }