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; }
static void Main () { string dir = AppDomain.CurrentDomain.BaseDirectory; XmlTextReader xtr = new XmlTextReader (Path.Combine (dir, "MyTestService.wsdl")); #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/", "http://schemas.xmlsoap.org/wsdl/"); settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/http/", "http://schemas.xmlsoap.org/wsdl/http/"); settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap/", "http://schemas.xmlsoap.org/wsdl/soap/"); settings.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap12/", "http://schemas.xmlsoap.org/wsdl/soap12/wsdl11soap12.xsd"); XmlReader vr = XmlReader.Create (xtr, settings); #else XmlValidatingReader vr = new XmlValidatingReader (xtr); vr.ValidationType = ValidationType.Schema; vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/", "http://schemas.xmlsoap.org/wsdl/"); vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/http/", "http://schemas.xmlsoap.org/wsdl/http/"); vr.Schemas.Add ("http://schemas.xmlsoap.org/wsdl/soap/", "http://schemas.xmlsoap.org/wsdl/soap/"); #endif while (vr.Read ()) { } }
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(); } }
public void ResolveEntity2() { string ent1 = "<!ENTITY ent 'entity string'>"; string ent2 = "<!ENTITY ent2 '<foo/><foo/>'>]>"; string dtd = "<!DOCTYPE root[<!ELEMENT root (#PCDATA|foo)*>" + ent1 + ent2; string xml = dtd + "<root>&ent3;&ent2;</root>"; dvr = new XmlValidatingReader(xml, XmlNodeType.Document, null); dvr.ValidationType = ValidationType.None; dvr.EntityHandling = EntityHandling.ExpandCharEntities; dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // &ent3; Assert.AreEqual(XmlNodeType.EntityReference, dvr.NodeType); // under .NET 2.0, an error is raised here. // under .NET 1.1, the error is thrown on the next read. try { dvr.ResolveEntity(); Assert.Fail("Attempt to resolve undeclared entity should fail."); } catch (XmlException) { } }
/// <summary> ///************************************************************************* /// Method: ValidateXmlDocument /// Description: loads the xml document and validates it using faults.dtd /// /// Parameters: /// xmlFileName - the path of the faults.xml file /// Return Value : None ///************************************************************************* /// </summary> public void ValidateXmlDocument(String xmlFileName) { XmlTextReader reader = new XmlTextReader(xmlFileName); XmlValidatingReader validator = new XmlValidatingReader(reader); validator.ValidationType = ValidationType.DTD; validator.ValidationEventHandler += new ValidationEventHandler(this.ValidationHandler); // do nothing in this loop, all errors will be handled by ValidationHandler while (validator.Read()) { } }
public void EnumerationFacetOnAttribute() { string xml = "<test mode='NOT A ENUMERATION VALUE' />"; XmlSchema schema = XmlSchema.Read(new XmlTextReader("Test/XmlFiles/xsd/79650.xsd"), null); XmlValidatingReader xvr = new XmlValidatingReader(xml, XmlNodeType.Document, null); xvr.ValidationType = ValidationType.Schema; xvr.Schemas.Add(schema); while (!xvr.EOF) { xvr.Read(); } }
[Test] // bug #79924 public void ValidationTypeNoneIgnoreSchemaLocations() { string xml = "<project xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='nosuchschema.xsd'/>"; XmlValidatingReader vr = new XmlValidatingReader( new XmlTextReader(new StringReader(xml))); vr.ValidationType = ValidationType.None; vr.XmlResolver = new XmlErrorResolver(); while (!vr.EOF) { vr.Read(); } }
/// <summary> /// Validation of the XML /// </summary> /// <param name="reader"></param> public static void Validate(XmlReader reader) { //TODO: looks a little odd this one XmlValidatingReader vr = new XmlValidatingReader(reader); vr.ValidationType = ValidationType.Auto; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); while (vr.Read()) { } ; }
public void TestMixedContent() { string intSubset = "<!ELEMENT root (#PCDATA | foo)*><!ELEMENT foo EMPTY>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root />"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // end xml = dtd + "<root>Test.</root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // valid PCDATA dvr.Read(); // endelement root xml = dtd + "<root><foo/>Test.<foo></foo></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // valid foo dvr.Read(); // valid #PCDATA dvr.Read(); // valid foo dvr.Read(); // valid endElement foo dvr.Read(); // valid endElement root xml = dtd + "<root>Test.<bar /></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // valid #PCDATA try { dvr.Read(); // invalid element Assert.Fail("should be failed."); } catch (XmlSchemaException) { } }
internal void Validate(string xmlString) { XmlTextReader tr = new XmlTextReader(new StringReader(xmlString)); XmlValidatingReader vr = new XmlValidatingReader(tr); vr.ValidationType = ValidationType.Auto; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); while (vr.Read()) { } ; }
public void TestSingleElement() { string intSubset = "<!ELEMENT root EMPTY>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root />"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); xml = dtd + "<invalid />"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD try { dvr.Read(); // invalid element. Assert.Fail("should be failed."); } catch (XmlSchemaException) { } xml = dtd + "<root>invalid PCDATA.</root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root try { dvr.Read(); // invalid text Assert.Fail("should be failed."); } catch (XmlSchemaException) { } xml = dtd + "<root><invalid_child /></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root try { dvr.Read(); // invalid child Assert.Fail("should be failed."); } catch (XmlSchemaException) { } }
public void TestExpandEntity() { string intSubset = "<!ELEMENT root (#PCDATA)><!ATTLIST root foo CDATA 'foo-def' bar CDATA 'bar-def'><!ENTITY ent 'entity string'>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root foo='&ent;' bar='internal &ent; value'>&ent;</root>"; dvr = PrepareXmlReader(xml); dvr.EntityHandling = EntityHandling.ExpandEntities; dvr.Read(); // DTD dvr.Read(); Assert.AreEqual(XmlNodeType.Element, dvr.NodeType); Assert.AreEqual("root", dvr.Name); Assert.IsTrue(dvr.MoveToFirstAttribute()); Assert.AreEqual("foo", dvr.Name); Assert.AreEqual("entity string", dvr.Value); Assert.IsTrue(dvr.MoveToNextAttribute()); Assert.AreEqual("bar", dvr.Name); Assert.AreEqual("internal entity string value", dvr.Value); Assert.AreEqual("entity string", dvr.ReadString()); // ValidationType = None dvr = PrepareXmlReader(xml); dvr.EntityHandling = EntityHandling.ExpandEntities; dvr.ValidationType = ValidationType.None; dvr.Read(); // DTD dvr.Read(); Assert.AreEqual(XmlNodeType.Element, dvr.NodeType); Assert.AreEqual("root", dvr.Name); Assert.IsTrue(dvr.MoveToFirstAttribute()); Assert.AreEqual("foo", dvr.Name); Assert.AreEqual("entity string", dvr.Value); Assert.IsTrue(dvr.MoveToNextAttribute()); Assert.AreEqual("bar", dvr.Name); Assert.AreEqual("internal entity string value", dvr.Value); Assert.AreEqual("entity string", dvr.ReadString()); }
public void TestReadTypedValueSimple() { string xml = "<root>12</root>"; XmlSchema schema = new XmlSchema(); XmlSchemaElement elem = new XmlSchemaElement(); elem.Name = "root"; elem.SchemaTypeName = new XmlQualifiedName("integer", XmlSchema.Namespace); schema.Items.Add(elem); // Lap 1: xvr = PrepareXmlReader(xml); xvr.Schemas.Add(schema); // Read directly from root. object o = xvr.ReadTypedValue(); Assert.AreEqual(ReadState.Initial, xvr.ReadState); Assert.IsNull(o); xvr.Read(); // element root Assert.AreEqual(XmlNodeType.Element, xvr.NodeType); Assert.IsNotNull(xvr.SchemaType); Assert.IsTrue(xvr.SchemaType is XmlSchemaDatatype); o = xvr.ReadTypedValue(); // read "12" Assert.AreEqual(XmlNodeType.EndElement, xvr.NodeType); Assert.IsNotNull(o); Assert.AreEqual(typeof(decimal), o.GetType()); decimal n = (decimal)o; Assert.AreEqual(12, n); Assert.IsTrue(!xvr.EOF); Assert.AreEqual("root", xvr.Name); Assert.IsNull(xvr.SchemaType); // EndElement's type // Lap 2: xvr = PrepareXmlReader(xml); xvr.Schemas.Add(schema); xvr.Read(); // root XmlSchemaDatatype dt = xvr.SchemaType as XmlSchemaDatatype; Assert.IsNotNull(dt); Assert.AreEqual(typeof(decimal), dt.ValueType); Assert.AreEqual(XmlTokenizedType.None, dt.TokenizedType); xvr.Read(); // text "12" Assert.IsNull(xvr.SchemaType); o = xvr.ReadTypedValue(); // ReadTypedValue is different from ReadString(). Assert.IsNull(o); }
static void Main(string[] args) { // Create a cache of schemas, and add two schemas XmlSchemaCollection list = new XmlSchemaCollection(); list.Add("", "../../Schemas/iPhone.xsd"); // Create a validating reader object XmlTextReader textReader = new XmlTextReader("../../Schemas/iPhone.xml"); XmlValidatingReader validReader = new XmlValidatingReader(textReader); validReader.ValidationType = ValidationType.Schema; validReader.Schemas.Add(list); // Register a validation event handler method validReader.ValidationEventHandler += new ValidationEventHandler(myEventHandler); try { int count = 0; while (validReader.Read()) { //if (validReader.NodeType == XmlNodeType.Attribute && validReader.Name == "TradeName") //{ // string name = validReader.ReadContentAsString(); // Console.WriteLine(name); //} if (validReader.NodeType == XmlNodeType.Element && validReader.LocalName == "Release-Date") { String value = validReader.ReadElementString(); Console.WriteLine("Release-Date: {0}", value); if (value != null) { count++; } } } Console.WriteLine("\nNumber of models is counted: {0}\n", count); } catch (XmlException e) { Console.WriteLine("XmlException occured: " + e.Message); } finally { Console.ReadKey(); validReader.Close(); } }
public void Validate(string strXMLDoc) { try { // Declare local objects XmlSchemaCollection xsc = null; XmlValidatingReader vr = null; // Text reader object XmlReader tr = XmlReader.Create("MetaMeta.xsd"); xsc = new XmlSchemaCollection(); xsc.Add(null, tr); // XML validator object vr = new XmlValidatingReader(strXMLDoc, XmlNodeType.Document, null); vr.Schemas.Add(xsc); // Add validation event handler vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); // Validate XML data while (vr.Read()) { ; } vr.Close(); // Raise exception, if XML validation fails if (ErrorsCount > 0) { throw new Exception(ErrorMessage); } // XML Validation succeeded Console.WriteLine("XML validation succeeded.\r\n"); } catch (Exception error) { // XML Validation failed Console.WriteLine("XML validation failed." + "\r\n" + "Error Message: " + error.Message); } }
public static void Main() { // Create the XML fragment to be parsed. string xmlFrag = @"<book> <misc> <style>paperback</style> <pages>240</pages> </misc> </book> "; // Create the XmlNamespaceManager. XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); // Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); // Create the reader. XmlValidatingReader reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); IXmlLineInfo lineInfo = ((IXmlLineInfo)reader); if (lineInfo.HasLineInfo()) { // Parse the XML and display each node. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: Console.Write("{0} {1},{2} ", reader.Depth, lineInfo.LineNumber, lineInfo.LinePosition); Console.WriteLine("<{0}>", reader.Name); break; case XmlNodeType.Text: Console.Write("{0} {1},{2} ", reader.Depth, lineInfo.LineNumber, lineInfo.LinePosition); Console.WriteLine(" {0}", reader.Value); break; case XmlNodeType.EndElement: Console.Write("{0} {1},{2} ", reader.Depth, lineInfo.LineNumber, lineInfo.LinePosition); Console.WriteLine("</{0}>", reader.Name); break; } } } // Close the reader. reader.Close(); }
private string MontaXmlConsultarSituacaoLoteRps(tcIdentificacaoPrestador objPrestador) { XmlSchemaCollection myschema = new XmlSchemaCollection(); XmlValidatingReader reader; try { XNamespace tipos = "http://www.ginfes.com.br/tipos_v03.xsd"; XNamespace pf = "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd"; XContainer conPrestador = null; XContainer conProtocolo = null; XContainer conConsultarLoteRpsEnvio = (new XElement(pf + "ConsultarSituacaoLoteRpsEnvio", new XAttribute("xmlns", "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd"), new XAttribute(XNamespace.Xmlns + "tipos", "http://www.ginfes.com.br/tipos_v03.xsd"))); conPrestador = (new XElement(pf + "Prestador", new XElement(tipos + "Cnpj", objPrestador.Cnpj), ((objPrestador.InscricaoMunicipal != "") ? new XElement(tipos + "InscricaoMunicipal", objPrestador.InscricaoMunicipal) : null))); conProtocolo = new XElement(pf + "Protocolo", Protocolo); conConsultarLoteRpsEnvio.Add(conPrestador); conConsultarLoteRpsEnvio.Add(conProtocolo); belAssinaXml Assinatura = new belAssinaXml(); string sArquivo = Assinatura.ConfigurarArquivo(conConsultarLoteRpsEnvio.ToString(), "Protocolo", Acesso.cert_NFs); XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); reader = new XmlValidatingReader(sArquivo, XmlNodeType.Element, context); myschema.Add("http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd", Pastas.SCHEMA_NFSE + "\\servico_consultar_situacao_lote_rps_envio_v03.xsd"); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } return(sArquivo); } catch (Exception ex) { throw ex; } }
private List <ValidationResult> ValidateSchema(string fileName, ValidationProfile profile, byte[] sourceData, XmlNamespaceManager nsManager) { Dictionary <string, string> namespaces = null; #pragma warning disable CS0618 // Type or member is obsolete XmlSchemaCollection schemas = new XmlSchemaCollection(); #pragma warning restore CS0618 // Type or member is obsolete schemas.Add(Helper.GetSchema(profile.SchemaLocation, out namespaces)); XmlParserContext context = new XmlParserContext(null, nsManager, null, XmlSpace.None); using (MemoryStream sourceStream = new MemoryStream(sourceData)) { #pragma warning disable CS0618 // Type or member is obsolete XmlValidatingReader validatingReader = new XmlValidatingReader(sourceStream, XmlNodeType.Document, context); #pragma warning restore CS0618 // Type or member is obsolete validatingReader.ValidationType = ValidationType.Schema; validatingReader.Schemas.Add(schemas); List <ValidationResult> results = new List <ValidationResult>(); ValidationResult newResult = null; validatingReader.ValidationEventHandler += new ValidationEventHandler(delegate(object sender, ValidationEventArgs e) { newResult = new ValidationResult() { FileName = fileName, ErrorMessage = e.Message, Severity = e.Severity.ToString(), TestContext = "Schema", Test = "N/A", Location = "N/A", LineNumber = e.Exception.LineNumber }; results.Add(newResult); }); while (validatingReader.Read()) { if (newResult != null) { newResult.Test = validatingReader.Name; results.Add(newResult); newResult = null; } } return(results); } }
private static void InitParams(MemoryStream sXML) { System.Xml.XmlDocument docGEN_XML = null; { sXML.Position = 0; isGEN_XMLValid = true; XmlSchemaCollection myschemacoll = new XmlSchemaCollection(); XmlValidatingReader vr; try { //Load the XmlValidatingReader. vr = new XmlValidatingReader(sXML, XmlNodeType.Element, null); //Add the schemas to the XmlSchemaCollection object. myschemacoll.Add("http://www.hafsjold.dk/schema/hafsjold.xsd", @"C:\_BuildTools\Generators\SPGenerator\hafsjold.xsd"); vr.Schemas.Add(myschemacoll); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ShowCompileErrors); while (vr.Read()) { } Console.WriteLine("Validation completed"); docGEN_XML = new System.Xml.XmlDocument(); sXML.Position = 0; docGEN_XML.Load(sXML); } catch { } finally { //Clean up. vr = null; myschemacoll = null; sXML = null; } } { string l_ns = "http://www.hafsjold.dk/schema/hafsjold.xsd"; XmlNamespaceManager l_nsMgr = new XmlNamespaceManager(docGEN_XML.NameTable); l_nsMgr.AddNamespace("mha", l_ns); System.Xml.XmlNode propertySets = docGEN_XML.SelectSingleNode("//mha:hafsjold/mha:propertySets", l_nsMgr); string SVNRootPath = propertySets.Attributes["SVNRootPath"].Value; DATASET_PATH = SVNRootPath + @"DATASET\"; } }
public override object Parse(string value, XmlReader reader) { // Now we create XmlValidatingReader to handle // simple-type based validation (since there is no // other way, because of sucky XmlSchemaSimpleType // design). XmlValidatingReader v = new XmlValidatingReader( new XmlTextReader( String.Concat("<root>", value, "</root>"), XmlNodeType.Document, null)); v.Schemas.Add(schema); v.Read(); // <root> try { return(v.ReadTypedValue()); } finally { v.Read(); // </root> } }
//============================== // static void XML_Validation_Old() { //<snippet3a> XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader("books.xml")); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add("urn:books", "books.xsd"); reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); while (reader.Read()) { ; } //</snippet3a> }
private void Validate() { try { while (xmlValidatingReader.Read()) { } } catch (Exception e) { Console.WriteLine("Exception: " + e.ToString()); throw e; } }
public static void Main(string[] args) { string UserName = args[0]; string SecurelyStoredPassword = args[1]; string Domain = args[2]; //<snippet1> // Create the reader. XmlTextReader txtreader = new XmlTextReader("book5.xml"); XmlValidatingReader reader = new XmlValidatingReader(txtreader); txtreader.WhitespaceHandling = WhitespaceHandling.None; // Set the credentials necessary to access the DTD file stored on the network. XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; reader.XmlResolver = resolver; // Display each of the element 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.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; } } //</snippet1> //Close the reader. reader.Close(); }
public void TestAny() { string intSubset = "<!ELEMENT root ANY><!ELEMENT foo EMPTY>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root />"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // empty root. dvr.Read(); // end of document. xml = dtd + "<root><foo/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo dvr.Read(); // end root xml = dtd + "<root><foo /><foo></foo><foo/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo dvr.Read(); // foo dvr.Read(); // foo dvr.Read(); // end root xml = dtd + "<root><bar /></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root try { dvr.Read(); // bar: invalid (undeclared) element Assert.Fail("should be failed."); } catch (XmlSchemaException) { } }
static void Validate (string xml, XmlSchema schema) { #if NET_2_0 XmlReaderSettings s = new XmlReaderSettings (); s.ValidationType = ValidationType.Schema; s.Schemas.Add (schema); XmlReader r = XmlReader.Create (new StringReader (xml), s); #else XmlTextReader xtr = new XmlTextReader (new StringReader (xml)); XmlValidatingReader r = new XmlValidatingReader (xtr); r.ValidationType = ValidationType.Schema; #endif while (!r.EOF) r.Read (); }
// bug #78985 (contains two identical field path "@key" in // two different keys where one is in scope within another) public void DuplicateKeyFieldAttributePath() { string schemaFileName = "Test/XmlFiles/xsd/78985.xsd"; string xmlFileName = "Test/XmlFiles/xsd/78985.xml"; XmlTextReader tr = new XmlTextReader(schemaFileName); XmlValidatingReader vr = new XmlValidatingReader( new XmlTextReader(xmlFileName)); vr.Schemas.Add(XmlSchema.Read(tr, null)); while (!vr.EOF) { vr.Read(); } }
static void ValidateDtd(string [] args) { for (int i = 1; i < args.Length; i++) { XmlValidatingReader xvr = new XmlValidatingReader( new XmlTextReader(args [i])); xvr.ValidationType = ValidationType.DTD; xvr.EntityHandling = EntityHandling.ExpandEntities; while (!xvr.EOF) { xvr.Read(); } xvr.Close(); } }
/// <summary> /// Validates the specified xml content /// </summary> /// <param name="sImportDocument">Xml content to validate</param> /// <returns>Error messages if any, else "true"</returns> public List <string> ValidateCrmImportDocument(string sImportDocument) { ValidationEventHandler eventHandler = ShowCompileErrors; XmlSchemaCollection myschemacoll = new XmlSchemaCollection(); XmlValidatingReader vr; try { using (StreamReader schemaReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MsCrmTools.SiteMapEditor.Resources.sitemap.xsd"))) { //Load the XmlValidatingReader. vr = new XmlValidatingReader(schemaReader.BaseStream, XmlNodeType.Element, null); vr.Schemas.Add(myschemacoll); vr.ValidationType = ValidationType.Schema; while (vr.Read()) { } } return(messages); } //This code catches any XML exceptions. catch (XmlException XmlExp) { messages.Add(XmlExp.Message); return(messages); } //This code catches any XML schema exceptions. catch (XmlSchemaException XmlSchemaExp) { messages.Add(XmlSchemaExp.Message); return(messages); } //This code catches any standard exceptions. catch (Exception GeneralExp) { messages.Add(GeneralExp.Message); return(messages); } finally { vr = null; myschemacoll = null; } }
static void Main(string[] args) { const string URL = "https://api.privatbank.ua/p24api/pboffice?city=%D0%9B%D1%8C%D0%B2%D0%BE%D0%B2"; const string FILE_NEW = @"D:\Student.xml"; //читання документа xml XmlTextReader read = new XmlTextReader(URL); while (read.Read()) { if (read.NodeType == XmlNodeType.Element) { if (read.AttributeCount >= 0) { read.MoveToAttribute("address"); System.Console.WriteLine(read.Value); } } } read.Close(); //створення документа xml XmlTextWriter write = new XmlTextWriter(FILE_NEW, Encoding.UTF8); write.Formatting = Formatting.Indented; write.WriteStartDocument(true); write.WriteStartElement("students"); write.WriteStartElement("student"); write.WriteAttributeString("id", "1"); write.WriteElementString("name", "Fedir"); write.WriteElementString("group", "s25-vp1"); write.WriteEndElement(); write.WriteEndElement(); write.Close(); //перевірка документа xml (XSD) //застаріла DTD XmlValidatingReader wr = new XmlValidatingReader(new XmlTextReader(FILE_NEW)); //обробник wr.ValidationEventHandler += (sender, ev) => { System.Console.WriteLine("NOT VALIDATE!!!"); }; //wr.ValidationType=ValidationType.None //ЗВИЧАЙНИЙ XmlTextReader wr.ValidationType = ValidationType.Auto; //задаєм схему (простір імен, ім'я файла) wr.Schemas.Add("", @".\XMLSchema1.xsd"); while (wr.Read()) { } }
static void Test1 (string xsdFile) { byte [] data = Encoding.UTF8.GetBytes (xml); using (MemoryStream xmlStream = new MemoryStream (data)) { XmlReader xmlReader = new XmlTextReader (xmlStream); XmlValidatingReader vr = new XmlValidatingReader (xmlReader); vr.ValidationType = ValidationType.Schema; vr.Schemas.Add (null, new XmlTextReader (xsdFile)); vr.Schemas.Add (null, new XmlTextReader ("http://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd")); while (vr.Read ()) { } } }
public void Update(IDataSet dataSet) { _sberrors = new StringBuilder(); //Hold temporary xml in memory. MemoryStream mem = new MemoryStream(); //Validate only changes to the dataset dataSet.GetChanges().WriteXml(mem, XmlWriteMode.IgnoreSchema); //Reset current position in the temporary memory representation. mem.Position = 0; //Read schema. XmlSchema sch; //We don't need the full path because the FileStream class can reads relative paths. using (FileStream fs = new FileStream(dataSet.SchemaFile, FileMode.Open)) { sch = XmlSchema.Read(fs, new ValidationEventHandler(this.OnValidation)); sch.Compile(new ValidationEventHandler(this.OnValidation)); } //Validate incoming data. XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(mem)); reader.Schemas.Add(sch); reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new ValidationEventHandler(this.OnValidation); //Read to end and check errors afterwards. while (reader.Read()) { } if (_sberrors.Length != 0) { throw new ArgumentException(_sberrors.ToString(), "BaseDataSet"); } SqlXmlCommand cmd = new SqlXmlCommand(_connection); cmd.CommandType = SqlXmlCommandType.DiffGram; cmd.SchemaPath = dataSet.SchemaFile; SqlXmlAdapter ad = new SqlXmlAdapter(cmd); //Update database with DataSet data. ad.Update(dataSet.GetState()); }
static void Main(string[] args) { // Create a cache of schemas, and add two schemas XmlSchemaCollection sc = new XmlSchemaCollection(); sc.Add("", "D:/university/database/mssql/lab5/task1XSDGENERATOR.xsd"); //sc.Add("", "../../../doctors.xsd"); // Create a validating reader object XmlTextReader tr = new XmlTextReader("D:/university/database/mssql/lab5/task1.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; while (vr.Read()) { if (vr.NodeType == XmlNodeType.Element && vr.LocalName == "C") { num++; vr.MoveToElement(); } } Console.WriteLine("Number of Clients: " + num + "\n"); } catch (XmlException ex) { Console.WriteLine("XMLException occurred: " + ex.Message); } finally { vr.Close(); } Console.Read(); }
private string NfeDadosMsg(string sJust) { XmlSchemaCollection myschema = new XmlSchemaCollection(); XmlValidatingReader reader; try { DataTable dt = BuscaProtocoloNFe(objPesquisa.sCD_NFSEQ); XNamespace xname = "http://www.portalfiscal.inf.br/nfe"; XDocument xdoc = new XDocument(new XElement(xname + "cancNFe", new XAttribute("versao", Acesso.versaoNFe), new XElement(xname + "infCanc", new XAttribute("Id", "ID" + objPesquisa.sCHAVENFE), new XElement(xname + "tpAmb", Acesso.TP_AMB), new XElement(xname + "xServ", "CANCELAR"), new XElement(xname + "chNFe", objPesquisa.sCHAVENFE), new XElement(xname + "nProt", dt.Rows[0]["cd_nprotnfe"].ToString()), new XElement(xname + "xJust", sJust)))); string sPath = Pastas.PROTOCOLOS + "\\" + objPesquisa.sCD_NFSEQ + "_ped-can.xml"; xdoc.Save(sPath); belAssinaXml assinaCanc = new belAssinaXml(); string sArquivoAssinado = assinaCanc.ConfigurarArquivo(sPath, "infCanc", Acesso.cert_NFe); StreamReader ler; ler = File.OpenText(sPath); XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); reader = new XmlValidatingReader(ler.ReadToEnd().ToString(), XmlNodeType.Element, context); myschema.Add("http://www.portalfiscal.inf.br/nfe", Pastas.SCHEMA_NFE + "\\cancNFe_v2.00.xsd"); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } return(sArquivoAssinado); } catch (Exception x) { throw new Exception(x.Message); } }
public static bool ValidateXmlAgainstSchema(string xmlFilename, string schemaFilename, out string errmsg) { bool blStatus = false; XmlValidatingReader validator = null; try { XmlTextReader xmlTRdr = new XmlTextReader(xmlFilename); validator = new XmlValidatingReader(xmlTRdr); validator.ValidationType = ValidationType.Schema; XmlSchemaCollection xmlSchColl = new XmlSchemaCollection(); xmlSchColl.Add(null, schemaFilename); validator.Schemas.Add(xmlSchColl); blValidateFail = false; validator.ValidationEventHandler += new ValidationEventHandler(ValidationEventHandler); while (validator.Read()) { if (blValidateFail) { break; } } if (blValidateFail) { blStatus = false; } else { blStatus = true; } } catch (XmlException ex) { PepsiLiteErrorHandling.WriteErrorLog(ex.ToString()); } finally { validator.Close(); } errmsg = strErrMSg; return(blStatus); }
private void Validate(String filename, ValidationType vt) { try { //Implement the readers. Set the ValidationType. txtreader = new XmlTextReader(filename); reader = new XmlValidatingReader(txtreader); reader.ValidationType = vt; //If the reader is set to validate, set the event handler. if (vt == ValidationType.None) { Console.WriteLine("\nParsing XML file " + filename.ToString()); } else { Console.WriteLine("\nValidating XML file " + filename.ToString()); m_success = true; //Set the validation event handler. reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); } // Read XML data while (reader.Read()) { } if (vt == ValidationType.None) { Console.WriteLine("Finished parsing file."); } else { Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful" : "failed")); } } finally { //Close the reader. if (reader != null) { reader.Close(); } } }
static void Main (string [] args) { string xsd = @" <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='TestClass'> <xs:complexType> <xs:sequence> <xs:element name='UnknownItemSerializer' type='UnknownItemSerializerType' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='UnknownItemSerializerType'> <xs:sequence> <xs:element name='DerivedClass_1'> <xs:complexType> <xs:sequence> <xs:element name='value' type='xs:integer' /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name='type' type='xs:string' use='required' /> </xs:complexType> </xs:schema> "; TestClass a = new TestClass (); DerivedClass_1 d1 = new DerivedClass_1 (); a.Item = d1; String s = a.ToString (); XmlTextReader xtr = new XmlTextReader (new StringReader (s)); XmlValidatingReader vr = new XmlValidatingReader (xtr); vr.Schemas.Add (XmlSchema.Read (new StringReader (xsd), null)); vr.ValidationType = ValidationType.Schema; while (vr.Read ()) { } }
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; }
static void Main (string [] args) { string file = args [0]; using (FileStream stream = new FileStream (file, FileMode.Open)) { XmlValidatingReader vr = new XmlValidatingReader (stream, XmlNodeType.Document, null); vr.Schemas.Add (null, "xml.xsd"); vr.Schemas.Add (null, "CodeList.xsd"); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler (ValidationHandler); while (vr.Read ()) ; } #if NET_2_0 XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add (null, "xml.xsd"); settings.Schemas.Add (null, "CodeList.xsd"); settings.ValidationEventHandler += new ValidationEventHandler (ValidationHandler); XmlReader reader = XmlReader.Create (file, settings); while (reader.Read ()) ; #endif }
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 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; }
static void RunValidTest (string subdir, bool isSunTest) { string basePath = @"xml-test-suite/xmlconf/" + subdir + @"/valid"; DirectoryInfo [] dirs = null; if (isSunTest) dirs = new DirectoryInfo [] {new DirectoryInfo (basePath)}; else dirs = new DirectoryInfo (basePath).GetDirectories (); foreach (DirectoryInfo di in dirs) { foreach (FileInfo fi in di.GetFiles ("*.xml")) { try { XmlTextReader xtr = new XmlTextReader (fi.FullName); xtr.Namespaces = false; xtr.Normalization = true; XmlReader xr = new XmlValidatingReader (xtr); while (!xr.EOF) xr.Read (); } catch (XmlException ex) { Console.WriteLine ("Incorrectly not-wf: " + subdir + "/" + di.Name + "/" + fi.Name + " " + ex.Message); } catch (XmlSchemaException ex) { Console.WriteLine ("Incorrectly invalid: " + subdir + "/" + di.Name + "/" + fi.Name + " " + ex.Message); } catch (Exception ex) { Console.WriteLine ("Unexpected Error: " + subdir + "/" + di.Name + "/" + fi.Name + "\n" + ex.Message); } } } }