/// <summary> /// Metodo para cargar los XSD(Solo se cargan una vez debido a que el proceso tarda aprox 2 minutos) /// </summary> private void cargarXSD() { #region ENVIO ENTRE EMPRESAS if (trEnvioSobre == null) { trEnvioSobre = new XmlTextReader(RutasXSD.RutaXsdEnvioCFEentreEmpresa); } if (trEempresas == null) { trEempresas = new XmlTextReader(RutasXSD.RutaXsdCFEEmpresasType); } #endregion ENVIO ENTRE EMPRESAS #region ENVIO CON DGI //if (trEnvioSobre == null) //{ // trEnvioSobre = new XmlTextReader(RutasXSD.RutaXsdEnvioSobre); //} #endregion ENVIO CON DGI #region XSD HOJAS(SIEMPRE SE USAN) if (trTipoDGI == null) { trTipoDGI = new XmlTextReader(RutasXSD.RutaXsdTipoDgi); } if (trTipoCFE == null) { trTipoCFE = new XmlTextReader(RutasXSD.RutaXsdTipoCfe); } #endregion XSD HOJAS(SIEMPRE SE USAN) if (xsc == null) { xsc = new XmlSchemaCollection(); try { //Se cargan los XSD al esquema xsc.Add(null, trTipoDGI); xsc.Add(null, trTipoCFE); xsc.Add(null, trEempresas);//no se usa con envio a DGI xsc.Add(null, trEnvioSobre); } catch (Exception ex) { app.MessageBox("ValidarSobre/CArgarXSD/Error: " + ex.ToString()); } } }
public SchemaCollectionSample() { //Load the schema collection. XmlSchemaCollection xsc = new XmlSchemaCollection(); xsc.Add("urn:bookstore-schema", schema); //XSD schema xsc.Add("urn:newbooks-schema", schema1); //XDR schema //Validate the files using schemas stored in the collection. Validate(doc1, xsc); //Should pass. Validate(doc2, xsc); //Should fail. Validate(doc3, xsc); //Should fail. }
public void TestAdd() { XmlSchemaCollection col = new XmlSchemaCollection(); XmlSchema schema = new XmlSchema(); XmlSchemaElement elem = new XmlSchemaElement(); elem.Name = "foo"; schema.Items.Add(elem); schema.TargetNamespace = "urn:foo"; col.Add(schema); col.Add(schema); // No problem !? XmlSchema schema2 = new XmlSchema(); schema2.Items.Add(elem); schema2.TargetNamespace = "urn:foo"; col.Add(schema2); // No problem !! schema.Compile(null); col.Add(schema); col.Add(schema); // Still no problem !!! schema2.Compile(null); col.Add(schema2); schema = GetSchema("Test/XmlFiles/xsd/3.xsd"); schema.Compile(null); col.Add(schema); schema2 = GetSchema("Test/XmlFiles/xsd/3.xsd"); schema2.Compile(null); col.Add(schema2); }
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(); } }
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 void DuplicateSchemaAssignment() { string xml = @"<data xmlns='http://www.test.com/schemas/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='http://www.test.com/schemas/ /home/user/schema.xsd' />" ; string xsd = @"<xs:schema targetNamespace='http://www.test.com/schemas/' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns='http://www.test.com/schemas/' > <xs:element name='data' /></xs:schema>" ; string xmlns = "http://www.test.com/schemas/"; XmlValidatingReader xvr = new XmlValidatingReader( xml, XmlNodeType.Document, null); XmlSchemaCollection schemas = new XmlSchemaCollection(); schemas.Add(XmlSchema.Read(new XmlTextReader( xsd, XmlNodeType.Document, null), null)); xvr.Schemas.Add(schemas); while (!xvr.EOF) { xvr.Read(); } }
//private static int MessageCount(string message) // calculate credits required to send this message; //{ // SettingDTO SettingDTO = new SettingDTO(); // Get limit on msg size // SettingDTO = SettingService.GetById(1); // int MAXMSGLENGTH = SettingDTO.MessageLength; // int MSGLENGTH = SettingDTO.SingleMessageLength; // if (message.Length <= MAXMSGLENGTH) // return 1; // else if (message.Length % MSGLENGTH != 0) // return (message.Length / MSGLENGTH) + 1; // else // return message.Length / MSGLENGTH; //} #endregion #region " Xmlpacket validation " private static bool ValidatePacketAgainstSchema(string xmlpacket) { XmlValidatingReader reader = null; XmlSchemaCollection myschema = new XmlSchemaCollection(); try { //Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); //Implement the reader. reader = new XmlValidatingReader(xmlpacket, XmlNodeType.Element, context); ////////Add the schema. //// myschema.Add(null, @"C:\inetpub\wwwroot\MsgBlasterWebServiceSetup\XmlSchema.xsd"); myschema.Add(null, ConfigurationManager.AppSettings["SchemaFile"].ToString()); //AppDomain.CurrentDomain.BaseDirectory + "\\XmlSchema.xsd" //myschema.Add(null, ConfigurationManager.AppSettings["SettingFiles"] + "XmlSchema.xsd"); //Set the schema type and add the schema to the reader. reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } } catch (Exception ex) { return(false); } return(true); }
public static void Main() { //<snippet1> XmlSchemaCollection sc = new XmlSchemaCollection(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Create a resolver with the necessary credentials. XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; // Add the new schema to the collection. sc.Add("", new XmlTextReader("sample.xsd"), resolver); //</snippet1> if (sc.Count > 0) { XmlTextReader tr = new XmlTextReader("notValidXSD.xml"); XmlValidatingReader rdr = new XmlValidatingReader(tr); rdr.ValidationType = ValidationType.Schema; rdr.Schemas.Add(sc); rdr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); while (rdr.Read()) { ; } } }
public clsSValidator(string sXMLFileName, string sSchemaFileName) { m_sXMLFileName = sXMLFileName; m_sSchemaFileName = sSchemaFileName; m_objXmlSchemaCollection = new XmlSchemaCollection(); //adding the schema file to the newly created schema collection m_objXmlSchemaCollection.Add(null, m_sSchemaFileName); }
static void Main(string[] args) { XmlSchemaCollection sc = new XmlSchemaCollection(); sc.Add("", "../../../../visual_studio_schema_test.xsd"); // Create a validating reader object XmlTextReader tr = new XmlTextReader("../../../../test_xml.xml"); //XmlTextReader tr = new XmlTextReader("../../../../xml_test_wrong_atrib.xml"); //XmlTextReader tr = new XmlTextReader("../../../../xml_test_wrong_root.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 == "Games") { num++; vr.MoveToFirstAttribute(); Console.WriteLine(vr.Value); vr.MoveToNextAttribute(); Console.WriteLine(vr.Value); vr.MoveToNextAttribute(); Console.WriteLine(vr.Value); vr.MoveToNextAttribute(); Console.WriteLine(vr.Value); vr.MoveToNextAttribute(); Console.WriteLine(vr.Value); vr.MoveToElement(); } } Console.WriteLine("Number of strings: " + num + "\n"); } catch (XmlException ex) { Console.WriteLine("XMLException occurred: " + ex.Message); } finally { vr.Close(); } }
static void Main(string[] args) { // Create a cache of schemas, and add two schemas XmlSchemaCollection sc = new XmlSchemaCollection(); sc.Add("urn:MyUri", "../../CompanySummaryNS.xsd"); sc.Add("", "../../CompanySummary.xsd"); // Create a validating reader object XmlTextReader tr = new XmlTextReader("../../CompanySummaryWithXSDAndNS.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 { while (vr.Read()) { if (vr.NodeType == XmlNodeType.Element && vr.LocalName == "NumEmps") { int num; num = XmlConvert.ToInt32(vr.ReadElementString()); Console.WriteLine("Number of employees: " + num); } } } catch (XmlException ex) { Console.WriteLine("XMLException occurred: " + ex.Message); } finally { vr.Close(); } }
private void Page_Load(object sender, System.EventArgs e) { XmlValidatingReader reader = null; XmlSchemaCollection myschema = new XmlSchemaCollection(); ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors); try { String xmlFrag = @"<?xml version='1.0' ?> <item> <xxx:price xmlns:xxx='xxx' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='test.xsd'></xxx:price> </item>"; /*"<author xmlns='urn:bookstore-schema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" + * "<first-name>Herman</first-name>" + * "<last-name>Melville</last-name>" + * "</author>";*/ string xsd = @"<?xml version='1.0' encoding='UTF-8'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema' targetNamespace='xxx'> <xsd:element name='price' type='xsd:integer' xsd:default='12'/> </xsd:schema>"; //Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); //Implement the reader. reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //Add the schema. myschema.Add("xxx", new XmlTextReader(new StringReader(xsd))); //Set the schema type and add the schema to the reader. reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { Response.Write(reader.Value); } Response.Write("<br>Completed validating xmlfragment<br>"); } catch (XmlException XmlExp) { Response.Write(XmlExp.Message + "<br>"); } catch (XmlSchemaException XmlSchExp) { Response.Write(XmlSchExp.Message + "<br>"); } catch (Exception GenExp) { Response.Write(GenExp.Message + "<br>"); } finally {} XmlDocument doc; }
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; string ProjectPath = propertySets.Attributes["ProjectPath"].Value; string ProjectName = propertySets.Attributes["ProjectName"].Value; PROJECT_DIR = SVNRootPath + ProjectPath; model = new Metadata(SVNRootPath); COREFILE = "ProvPur"; FILENAME_FIELDS = PROJECT_DIR + @"TEMPLATE\FEATURES\ProvPurFields\fields.xml"; FILENAME_DK = PROJECT_DIR + @"Resources\" + COREFILE + ".da-dk.resx"; FILENAME_UK = PROJECT_DIR + @"Resources\" + COREFILE + ".resx"; } }
private void LoadSchema() { Assembly assembly = this.GetType().Assembly; Stream stream = assembly.GetManifestResourceStream("DNPreBuild.data." + m_Schema); XmlReader schema = new XmlTextReader(stream); m_Schemas = new XmlSchemaCollection(); m_Schemas.Add(m_SchemaURI, schema); }
/// <summary> /// Get the schemas required to validate a library. /// </summary> /// <returns>The schemas required to validate a library.</returns> internal static XmlSchemaCollection GetSchemas() { if (null == schemas) { Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream librarySchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.libraries.xsd")) { schemas = new XmlSchemaCollection(); schemas.Add(Intermediate.GetSchemas()); schemas.Add(Localization.GetSchemas()); XmlSchema librarySchema = XmlSchema.Read(librarySchemaStream, null); schemas.Add(librarySchema); } } return(schemas); }
/// <summary> /// ITestStep.Execute() implementation /// </summary> /// <param name='data'>The stream cintaining the data to be validated.</param> /// <param name='context'>The context for the test, this holds state that is passed beteen tests</param> public void ExecuteValidation(Stream data, Context context) { var doc = new XmlDocument(); var trData = new XmlTextReader(data); var vr = new XmlValidatingReader(trData); // If schema was specified use it to vaidate against... if (null != _xmlSchemaPath) { MemoryStream xsdSchema = StreamHelper.LoadFileToStream(_xmlSchemaPath); var trSchema = new XmlTextReader(xsdSchema); var xsc = new XmlSchemaCollection(); if (null != _xmlSchemaNameSpace) { xsc.Add(_xmlSchemaNameSpace, trSchema); vr.Schemas.Add(xsc); } doc.Load(vr); } data.Seek(0, SeekOrigin.Begin); doc.Load(data); foreach (Pair validation in _xPathValidations) { var xpathExp = (string)validation.First; var expectedValue = (string)validation.Second; context.LogInfo("XmlValidationStepEx evaluting XPath {0} equals \"{1}\"", xpathExp, expectedValue); XPathNavigator xpn = doc.CreateNavigator(); object result = xpn.Evaluate(xpathExp); string checkValue = null; if (result.GetType().Name == "XPathSelectionIterator") { var xpi = result as XPathNodeIterator; xpi.MoveNext(); // BUGBUG! if (null != xpi) { checkValue = xpi.Current.ToString(); } } else { checkValue = result.ToString(); } if (0 != expectedValue.CompareTo(checkValue)) { throw new ApplicationException(string.Format("XmlValidationStepEx failed, compare {0} != {1}, xpath query used: {2}", expectedValue, checkValue, xpathExp)); } } }
string HandleLocationRequest(string msgLocationReq) { // Retrieve taxi position and return in location_update message XmlTextReader reader = new XmlTextReader(msgLocationReq, XmlNodeType.Document, null); XmlValidatingReader validReader = new XmlValidatingReader(reader); validReader.ValidationType = ValidationType.Schema; // Load the schema for validation purposes XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); try { schemaCollection.Add(null, @"C:\Inetpub\wwwroot\MPKService\MPK_HTD.xsd"); validReader.Schemas.Add(schemaCollection); validReader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); } catch (Exception e) { Debug.WriteLine(e.Message); } XPathDocument xpathdoc; try { xpathdoc = new XPathDocument(validReader, XmlSpace.Preserve); } catch (XmlException e) { return("<?xml version=\"1.0\" ?><envelope><error>" + e.Message + "</error></envelope>"); } XPathNavigator xpathNav = xpathdoc.CreateNavigator(); string xpathQuery = "/envelope/location_request/vehicle"; XPathNodeIterator xpathIter = xpathNav.Select(xpathQuery); StringWriter sw = new StringWriter(); try { while (xpathIter.MoveNext()) { sw.WriteLine("VEH_NBR: {0}", xpathIter.Current.Value); } } catch (XmlException e) { return("<?xml version=\"1.0\" ?><envelope><error>" + e.Message + "</error></envelope>"); } return(msgLocationReq); }
public static IDocumentPlug CreateDocumentPlug(XmlSchema schema) { XmlSchemaCollection set = new XmlSchemaCollection(); set.Add(schema); string targetNamespace; string name = ExtractNamespaceandRootnodeName(schema, out targetNamespace); return(CreateDocumentPlug(set, targetNamespace, name)); }
public void TestAddDoesCompilation() { XmlSchema schema = new XmlSchema(); Assert.IsFalse(schema.IsCompiled); XmlSchemaCollection col = new XmlSchemaCollection(); col.Add(schema); Assert.IsTrue(schema.IsCompiled); }
/// <SUMMARY> /// This method validates an xml string against an xml schema. /// </SUMMARY> /// <PARAM name="xml">StringReader containing xml</PARAM> /// <PARAM name="schemaNamespace">XML Schema Namespace</PARAM> /// <PARAM name="schemaUri">XML Schema Uri</PARAM> /// <RETURNS>bool</RETURNS> public bool ValidXmlDoc(StringReader xml, string schemaNamespace, string schemaUri) { // Continue? if (xml == null || schemaNamespace == null || schemaUri == null) { return(false); } isValidXml = true; XmlValidatingReader vr; XmlTextReader tr; XmlSchemaCollection schemaCol = new XmlSchemaCollection(); schemaCol.Add(schemaNamespace, schemaUri); try { // Read the xml. tr = new XmlTextReader(xml); // Create the validator. vr = new XmlValidatingReader(tr); // Set the validation tyep. vr.ValidationType = ValidationType.Auto; // Add the schema. if (schemaCol != null) { vr.Schemas.Add(schemaCol); } // Set the validation event handler. vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Read the xml schema. while (vr.Read()) { } vr.Close(); return(isValidXml); } catch (Exception ex) { this.ValidationError = ex.Message; this.isValidXml = false; return(false); } finally { // Clean up... vr = null; tr = null; } }
public static void AddSchema(string ns, string filename) { Debug.Verify( File.Exists(filename), "UDDI_ERROR_FATALERROR_SCHEMEMISSING", ErrorType.E_fatalError, filename ); xsc.Add(ns, filename); }
/// <summary> /// Get the schemas required to validate a pdb. /// </summary> /// <returns>The schemas required to validate a pdb.</returns> internal static XmlSchemaCollection GetSchemas() { lock (lockObject) { if (null == schemas) { Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream pdbSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.pdbs.xsd")) { schemas = new XmlSchemaCollection(); schemas.Add(Output.GetSchemas()); XmlSchema pdbSchema = XmlSchema.Read(pdbSchemaStream, null); schemas.Add(pdbSchema); } } } return(schemas); }
public static void Main() { //Create the schema collection. XmlSchemaCollection xsc = new XmlSchemaCollection(); //Set an event handler to manage invalid schemas. xsc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); //Add the schema to the collection. xsc.Add(null, "invalid.xsd"); }
public static IDocumentPlug CreateDocumentPlug(Stream schemaStream) { XmlTextReader reader = new XmlTextReader(schemaStream); XmlSchema schema = XmlSchema.Read(reader, null); XmlSchemaCollection set = new XmlSchemaCollection(); set.Add(schema); string targetNamespace; string name = ExtractNamespaceandRootnodeName(schema, out targetNamespace); return(CreateDocumentPlug(set, targetNamespace, name)); }
/// <summary> /// Get the schemas required to validate an object. /// </summary> /// <returns>The schemas required to validate an object.</returns> internal static XmlSchemaCollection GetSchemas() { lock (lockObject) { if (null == schemas) { Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream outputSchemaStream = assembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.outputs.xsd")) { schemas = new XmlSchemaCollection(); schemas.Add(Intermediate.GetSchemas()); schemas.Add(TableDefinitionCollection.GetSchemas()); XmlSchema outputSchema = XmlSchema.Read(outputSchemaStream, null); schemas.Add(outputSchema); } } } return(schemas); }
[Test] // bug #78220 public void TestCompile() { string schemaFragment1 = string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSDate\" elementFormDefault=\"qualified\" targetNamespace=\"NSDate\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:import namespace=\"NSStatus\" />{0}" + " <xs:element name=\"trans\" type=\"tns:TranslationStatus\" />{0}" + " <xs:complexType name=\"TranslationStatus\">{0}" + " <xs:simpleContent>{0}" + " <xs:extension xmlns:q1=\"NSStatus\" base=\"q1:StatusType\">{0}" + " <xs:attribute name=\"Language\" type=\"xs:int\" use=\"required\" />{0}" + " </xs:extension>{0}" + " </xs:simpleContent>{0}" + " </xs:complexType>{0}" + "</xs:schema>", Environment.NewLine); string schemaFragment2 = string.Format(CultureInfo.InvariantCulture, "<?xml version=\"1.0\" encoding=\"utf-16\"?>{0}" + "<xs:schema xmlns:tns=\"NSStatus\" elementFormDefault=\"qualified\" targetNamespace=\"NSStatus\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">{0}" + " <xs:simpleType name=\"StatusType\">{0}" + " <xs:restriction base=\"xs:string\">{0}" + " <xs:enumeration value=\"Untouched\" />{0}" + " <xs:enumeration value=\"Touched\" />{0}" + " <xs:enumeration value=\"Complete\" />{0}" + " <xs:enumeration value=\"None\" />{0}" + " </xs:restriction>{0}" + " </xs:simpleType>{0}" + "</xs:schema>", Environment.NewLine); XmlSchema schema1 = XmlSchema.Read(new StringReader(schemaFragment1), null); XmlSchema schema2 = XmlSchema.Read(new StringReader(schemaFragment2), null); XmlSchemaCollection schemas = new XmlSchemaCollection(); schemas.Add(schema2); schemas.Add(schema1); Assert.IsTrue(schema1.IsCompiled, "#1"); Assert.IsTrue(schema2.IsCompiled, "#2"); }
public void Validate(string strXMLDoc) { try { // Declare local objects XmlTextReader tr = null; XmlSchemaCollection xsc = null; XmlValidatingReader vr = null; // Text reader object tr = new XmlTextReader(urlpath); 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 SchemaValidator(string xmlFile, string schemaFile) { XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(); myXmlSchemaCollection.Add(XmlSchema.Read(new XmlTextReader(schemaFile), null)); // Validate the XML file with the schema XmlTextReader myXmlTextReader = new XmlTextReader(xmlFile); myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader); myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection); myXmlValidatingReader.ValidationType = ValidationType.Schema; }
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; } }
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(); } }
static void Main () { string dir = AppDomain.CurrentDomain.BaseDirectory; using (Stream input = File.OpenRead (Path.Combine (dir, "test.xml"))) { #if NET_2_0 XmlSchemaSet schemas = new XmlSchemaSet (); #else XmlSchemaCollection schemas = new XmlSchemaCollection (); #endif schemas.Add (XmlSchema.Read (File.OpenRead (Path.Combine (dir, "spring-objects.xsd")), null)); XmlReader reader = CreateValidatingReader (input, schemas, null); XmlDocument doc = new XmlDocument (); doc.Load (reader); } }
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."; }
/// <summary> /// Main entry point for sample application. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { XmlSchema myXmlSchema; XmlTextWriter myXmlTextWriter; try { Console.WriteLine ("Creating Schema in the Schema Object Model..."); // Setup console output. myXmlTextWriter = new XmlTextWriter(Console.Out); myXmlTextWriter.Formatting = Formatting.Indented; myXmlTextWriter.Indentation = 2; //Create an XmlNameTable. XmlNameTable myXmlNameTable = new NameTable(); //Add the nametable to the XmlSchemaCollection. XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(myXmlNameTable); //Add some schemas to the XmlSchemaCollection. Console.WriteLine ("Reading and adding {0} schema.", BOOKSCHEMA); myXmlSchemaCollection.Add(null, BOOKSCHEMA); Console.WriteLine ("Reading and adding {0} schema.", POSCHEMA); myXmlSchemaCollection.Add(null, POSCHEMA); Console.WriteLine ("Added schemas successfully ..."); Console.WriteLine ("Showing added schemas"); foreach(XmlSchema myTempXmlSchema in myXmlSchemaCollection) { myXmlSchema = myTempXmlSchema; Console.WriteLine(); string outfile = myTempXmlSchema.SourceUri.Replace("file:///", ""); Console.WriteLine("Schema from: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Schema ==="); Console.WriteLine(); // Write out the various schema parts WriteXSDSchema(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Schema ==="); Console.WriteLine(); Console.WriteLine("Example of possible XML contents for: {0}", outfile); Console.WriteLine(); Console.WriteLine("=== Start of Example ==="); // Write out an example of the XML for the schema WriteExample(myXmlSchema, myXmlTextWriter); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("=== End of Example ==="); } //foreach } //try catch (Exception e) { Console.WriteLine ("Exception: {0}", e.ToString()); } //catch } //Main()