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[] 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 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 ()) { } }
public static void Main(String[] args) { XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(args[0])); if (args[1] == "false") reader.ValidationType = ValidationType.None; else { reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new ValidationEventHandler (ValidationHandler); } XmlDocument doc = new XmlDocument(); doc.Load(reader); doc.Normalize(); XmlElement root = doc.DocumentElement; XmlNodeList titles = root.GetElementsByTagName("title"); for (int i=0; i < titles.Count; i++) { XmlNode title = titles[i]; XmlAttribute fullAt = title.Attributes["full"]; String full; if (fullAt == null) full = "true"; else full = fullAt.Value; XmlNode text = title.FirstChild; String result = (full=="false") ? "is not" : "is"; Console.WriteLine("{0} {1} the full title.", text.OuterXml, result); } }
static XmlReader CreateValidatingReader (Stream stream, XmlSchemaCollection schemas, ValidationEventHandler eventHandler) { XmlValidatingReader reader = new XmlValidatingReader (new XmlTextReader (stream)); reader.Schemas.Add (schemas); reader.ValidationType = ValidationType.Schema; if (eventHandler != null) reader.ValidationEventHandler += eventHandler; return reader; }
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(); } }
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 (); }
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 ()) { } } }
static int Main () { ValidationError ve = null; 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); settings.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); _reader = XmlReader.Create (new XmlTextReader ("input.xml"), settings); while (_reader.Read ()) ; _reader.Close (); if (_validationErrors.Count != 1) return 1; ve = (ValidationError) _validationErrors [0]; if (ve.LocalName != "myfield3") return 2; if (ve.NamespaceURI.Length != 0) return 3; #endif _validationErrors.Clear (); XmlValidatingReader vr = new XmlValidatingReader (new XmlTextReader ("input.xml")); vr.ValidationType = ValidationType.Schema; vr.Schemas.Add (schema); vr.ValidationEventHandler += new ValidationEventHandler (ValidationCallBack); _reader = vr; while (_reader.Read ()) ; if (_validationErrors.Count != 1) return 1; ve = (ValidationError) _validationErrors [0]; if (ve.LocalName != "myfield3") return 2; if (ve.NamespaceURI.Length != 0) return 3; return 0; }
public void Load(string url, XmlResolver resolver) { XmlResolver res = resolver; if (res == null) { res = new XmlUrlResolver(); } Uri uri = res.ResolveUri(null, url); using (Stream s = res.GetEntity(uri, null, typeof(Stream)) as Stream) { XmlTextReader xtr = new XmlTextReader(uri.ToString(), s); xtr.XmlResolver = res; XmlValidatingReader xvr = new XmlValidatingReader(xtr); xvr.XmlResolver = res; xvr.ValidationType = ValidationType.None; Load(new XPathDocument(xvr, XmlSpace.Preserve).CreateNavigator(), resolver, null); } }
static void ValidateXsd(string [] args) { XmlTextReader schemaxml = new XmlTextReader(args [1]); XSchema xsd = XSchema.Read(schemaxml, null); schemaxml.Close(); xsd.Compile(null); for (int i = 2; i < args.Length; i++) { XmlTextReader xtr = new XmlTextReader(args [i]); XmlValidatingReader xvr = new XmlValidatingReader(xtr); xvr.Schemas.Add(xsd); while (!xvr.EOF) { xvr.Read(); } xvr.Close(); } }
private XmlReader CreateXmlReader(XmlInput forInput) { XmlReader xmlReader = forInput.CreateXmlReader(); if (xmlReader is XmlTextReader) { ((XmlTextReader)xmlReader).WhitespaceHandling = _diffConfiguration.WhitespaceHandling; } if (_diffConfiguration.UseValidatingParser) { #pragma warning disable 612,618 XmlValidatingReader validatingReader = new XmlValidatingReader(xmlReader); #pragma warning restore 612,618 return(validatingReader); } return(xmlReader); }
internal Validator(XmlNameTable nameTable, SchemaNames schemaNames, XmlValidatingReader reader) { this.nameTable = nameTable; this.schemaNames = schemaNames; this.reader = reader; positionInfo = PositionInfo.GetPositionInfo(reader); nsManager = reader.NamespaceManager; if (nsManager == null) { nsManager = new XmlNamespaceManager(nameTable); isProcessContents = true; } SchemaInfo = new SchemaInfo(schemaNames); validationStack = new HWStack(STACK_INCREMENT); textValue = new StringBuilder(); this.name = XmlQualifiedName.Empty; attPresence = new Hashtable(); context = null; attnDef = null; }
/// <summary> /// Returns a validating XML document for a given <em>System.IO.Stream</em>. /// </summary> /// <param name="stream"> /// <em>System.IO.Stream</em> from which XML data needs to be read. /// </param> /// <returns> /// A <em>System.Xml.XmlDocument</em> if the stream contains valid XML /// data, an exception otherwise.</returns> public static XmlDocument GetValidatedXMLDocument(Stream stream) { if (stream == null) { throw new System.ArgumentNullException("stream", "The parameter [stream] is null. Cannot create an XML document."); } XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(stream)); reader.EntityHandling = EntityHandling.ExpandEntities; reader.ValidationType = ValidationType.Auto; XmlDocument document = new XmlDocument(); document.Load(reader); return(document); }
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 ()) { } }
public static bool Validate(XmlReader reader, XmlSchema schema) { XmlValidatingReader reader2; if (reader == null) { throw new ArgumentNullException("reader"); } if (schema == null) { throw new ArgumentNullException("schema"); } if (reader is XmlValidatingReader) { reader2 = (XmlValidatingReader)reader; } else { reader2 = new XmlValidatingReader(reader); } if (!reader2.Schemas.Contains(schema)) { reader2.Schemas.Add(schema); } reader2.ValidationType = ValidationType.Schema; reader2.ValidationEventHandler += new ValidationEventHandler(XmlSchemaUtil.ValidationHandler); try { while (reader.Read()) { } return(true); } catch { } finally { reader2.ValidationEventHandler -= new ValidationEventHandler(XmlSchemaUtil.ValidationHandler); } return(false); }
public static void AppendSchema(XmlValidatingReader reader, XmlSchema schema) { if (reader == null) { throw new ArgumentNullException("reader"); } if (schema == null) { throw new ArgumentNullException("schema"); } if (!reader.Schemas.Contains(schema.TargetNamespace)) { XmlSchemaCollection schemas; lock ((schemas = reader.Schemas)) { if (reader.Schemas.Contains(schema.TargetNamespace)) { return; } } if (!reader.Schemas.Contains(schema)) { lock ((schemas = reader.Schemas)) { if (reader.Schemas.Contains(schema)) { return; } } try { reader.Schemas.Add(schema); } catch (Exception ex) { Console.WriteLine(ex.Message); } reader.ValidationType = ValidationType.Schema; reader.ValidationEventHandler += new ValidationEventHandler(XmlSchemaUtil.ValidationHandler); } } }
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) { } }
// imported testcase from sys.security which had regression. public void ResolveEntityAndBaseURI() { try { using (TextWriter w = File.CreateText("world.txt")) { w.WriteLine("world"); } using (TextWriter w = File.CreateText("doc.dtd")) { w.WriteLine("<!-- dummy -->"); } string xml = "<!DOCTYPE doc SYSTEM \"doc.dtd\" [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + "<!ENTITY ent2 SYSTEM \"world.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + "<!-- Let world.txt contain \"world\" (excluding the quotes) -->\n"; XmlValidatingReader xvr = new XmlValidatingReader( xml, XmlNodeType.Document, null); xvr.ValidationType = ValidationType.None; xvr.EntityHandling = EntityHandling.ExpandCharEntities; XmlDocument doc = new XmlDocument(); doc.Load(xvr); } finally { if (File.Exists("world.txt")) { File.Delete("world.txt"); } if (File.Exists("doc.dtd")) { File.Delete("doc.dtd"); } } }
public bool ValidateXMLFile() { XmlTextReader objXmlTextReader = null; XmlValidatingReader objXmlValidatingReader = null; try { //creating a text reader for the XML file already picked by the //overloaded constructor above viz..clsSchemaValidator objXmlTextReader = new XmlTextReader(m_sXMLFileName); //creating a validating reader for that objXmlTextReader just created objXmlValidatingReader = new XmlValidatingReader(objXmlTextReader); //For validation we are adding the schema collection in //ValidatingReaders Schema collection. objXmlValidatingReader.Schemas.Add(m_objXmlSchemaCollection); //Attaching the event handler now in case of failures objXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler (ValidationFailed); //Actually validating the data in the XML file with a empty while. //which would fire the event ValidationEventHandler and invoke //our ValidationFailed function while (objXmlValidatingReader.Read()) { } //Note:- If any issue is faced in the above while it will invoke ValidationFailed //which will in turn set the module level m_bIsFailure boolean variable to false //thus returning true as a signal to the calling function that the ValidateXMLFile //function(this function) has encountered failure return(m_bIsFailure); } catch (Exception ex) { MessageBox.Show("Exception : " + ex.Message); return(true); } finally { // close the readers, no matter what. objXmlValidatingReader.Close(); objXmlTextReader.Close(); } }
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 Validate(string xmlFilePath, XmlSchemaCollection schemaCol, bool logError, string logFile) { _logError = logError; _logFile = logFile; _xmlFilePath = xmlFilePath; _valid = true; try { xmlReader = new XmlTextReader(_xmlFilePath); vReader = new XmlValidatingReader(xmlReader); if (schemaCol != null) { vReader.Schemas.Add(schemaCol); } vReader.ValidationType = ValidationType.Auto; /* Provide your own resolver if implementing a custom * caching mechnism * XmlUrlResolver resolver = new XmlUrlResolver(); * vReader.XmlResolver = resolver; */ vReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallBack); // Parse through XML while (vReader.Read()) { } } catch { _valid = false; } finally { //Close our readers if (xmlReader.ReadState != ReadState.Closed) { xmlReader.Close(); } if (vReader.ReadState != ReadState.Closed) { vReader.Close(); } } return(_valid); }
private string NfeCabecMsg() { try { XNamespace ns2 = "http://www.ginfes.com.br/cabecalho_v03.xsd"; XContainer xdoc = (new XElement(ns2 + "cabecalho", new XAttribute("versao", "3"), new XAttribute(XNamespace.Xmlns + "ns2", "http://www.ginfes.com.br/cabecalho_v03.xsd"), new XElement("versaoDados", "3"))); //<ns2:cabecalho versao="3" xmlns:ns2="http://www.ginfes.com.br/cabecalho_v03.xsd"> // <versaoDados>3</versaoDados> //</ns2:cabecalho> XmlSchemaCollection myschema = new XmlSchemaCollection(); XmlValidatingReader reader; XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); reader = new XmlValidatingReader(xdoc.ToString(), XmlNodeType.Element, context); myschema.Add("http://www.ginfes.com.br/cabecalho_v03.xsd", Pastas.SCHEMA_NFSE + "\\cabecalho_v03.xsd"); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } return(xdoc.ToString()); } catch (XmlException x) { throw new Exception(x.Message.ToString()); } catch (XmlSchemaException x) { throw new Exception(x.Message.ToString()); } }
private XmlNode MontaMsg() { try { XmlSchemaCollection myschema = new XmlSchemaCollection(); XmlValidatingReader reader; XNamespace pf = "http://www.portalfiscal.inf.br/nfe"; XDocument xdoc = new XDocument(new XElement(pf + "ConsCad", new XAttribute("versao", "2.00"), new XElement(pf + "infCons", new XElement(pf + "xServ", "CONS-CAD"), new XElement(pf + "UF", sUF), (sIE != "" ? new XElement(pf + "IE", (sIE != "" ? Util.TiraSimbolo(sIE, "") : "ISENTO")) : null), ((sCNPJ != "" && sIE == "") ? new XElement(pf + "CNPJ", Util.TiraSimbolo(sCNPJ, "")) : null), ((sCPF != "" && sIE == "" && sCNPJ == "") ? new XElement(pf + "CPF", Util.TiraSimbolo(sCPF, "")) : null)))); XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None); reader = new XmlValidatingReader(xdoc.ToString(), XmlNodeType.Element, context); myschema.Add("http://www.portalfiscal.inf.br/nfe", Pastas.SCHEMA_NFE + "\\consCad_v2.00.xsd"); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(myschema); while (reader.Read()) { } string sDados = xdoc.ToString(); XmlDocument Xmldoc = new XmlDocument(); Xmldoc.LoadXml(sDados); XmlNode xNode = Xmldoc.DocumentElement; return(xNode); } catch (Exception ex) { throw; } }
private void Render(Stream stream, string xslResourceId, string xslResourceDefault, XsltArgumentList args) { XslTransform xslt = new XslTransform(); xslt.Load(new XmlTextReader(Assembly .GetExecutingAssembly() .GetManifestResourceStream(Parameter.GetString(xslResourceId, xslResourceDefault))), null, null); XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(ruleFileURI)); reader.ValidationType = ValidationType.Schema; reader.Schemas.Add(XmlSchema.Read(Assembly .GetExecutingAssembly() .GetManifestResourceStream(Parameter.GetString("xbusinessrules.xsd", "xBusinessRules.xsd")), null)); xslt.Transform(new XPathDocument(reader), args, stream, null); reader.Close(); }
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> } }
private void ValidXml() { XmlTextReader tr = new XmlTextReader("HeadCount.xml"); XmlValidatingReader vr = new XmlValidatingReader(tr); // XmlReader xr = vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); while (vr.Read()) { // PrintTypeInfo(vr); if (vr.NodeType == XmlNodeType.Element) { // while (vr.MoveToNextAttribute()) // PrintTypeInfo(vr); } } // Console.WriteLine("Validation finished"); }
private void Validate(String filename) { m_success = true; Console.WriteLine("\r\n******"); Console.WriteLine("Validating XML file " + filename.ToString()); XmlTextReader txtreader = new XmlTextReader(filename); XmlValidatingReader reader = new XmlValidatingReader(txtreader); // Set the validation event handler reader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // Read XML data while (reader.Read()) { } Console.WriteLine("Validation finished. Validation {0}", (m_success == true ? "successful!" : "failed.")); //Close the reader. reader.Close(); }
// MS fails to validate nondeterministic content validation. public void TestNonDeterministicContent() { string intSubset = "<!ELEMENT root ((foo, bar)|(foo,baz))><!ELEMENT foo EMPTY><!ELEMENT bar EMPTY><!ELEMENT baz EMPTY>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root><foo/><bar/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo dvr.Read(); // bar dvr.Read(); // end root xml = dtd + "<root><foo/><baz/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo dvr.Read(); // end root }
/// <summary> /// Validation through XML Schema. /// </summary> /// <param name="schemaFile"></param> /// <param name="docFile"></param> public static void Validate(string schemaFile, string docFile) { XmlSchemaCollection sc = new XmlSchemaCollection(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); sc.Add(null, schemaFile); XmlTextReader tr = new XmlTextReader(docFile); XmlValidatingReader vr = new XmlValidatingReader(tr); vr.Schemas.Add(sc); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); while (vr.Read()) { ; } MessageBox.Show(null, "Validation finished", "Info"); }
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."; }
public XmlNode GetNodeByUri(string absoluteUrl) { absoluteUrl = absoluteUrl.Trim(); if (absoluteUrl.StartsWith("#")) { return(GetElementById(absoluteUrl.Substring(1))); } else { Uri docUri = ResolveUri(""); Uri absoluteUri = new Uri(absoluteUrl); string fragment = absoluteUri.Fragment; if (fragment.Length == 0) { // no fragment => return entire document if (docUri.AbsolutePath == absoluteUri.AbsolutePath) { return(this); } else { SvgDocument doc = new SvgDocument((SvgWindow)Window); XmlTextReader xtr = new XmlTextReader(absoluteUri.AbsolutePath, GetResource(absoluteUri).GetResponseStream()); XmlValidatingReader vr = new XmlValidatingReader(xtr); vr.ValidationType = ValidationType.None; doc.Load(vr); return(doc); } } else { // got a fragment => return XmlElement string noFragment = absoluteUri.AbsoluteUri.Replace(fragment, ""); SvgDocument doc = (SvgDocument)GetNodeByUri(new Uri(noFragment, true)); return(doc.GetElementById(fragment.Substring(1))); } } }
private static XmlDocument GetXmlDoc(FileStream fileXML, string path) { errorCode = ErrorCode.NoError; try { // Validazione file XML xmlDoc = new XmlDocument(); // Modifica Sam: durante la creazione dei report mi sono accorto che path contiene // già il nome del file schema! Comunque finché non scopro se effettivamente l'istruzione // seguente è errata, l'ho commentata e c'ho messo quella che segue //string reportXSD = path + "XMLReport.xsd"; string reportXSD; if (!path.EndsWith("XMLReport.xsd")) { reportXSD = path + "XMLReport.xsd"; } else { reportXSD = path; } XmlTextReader xtr = new XmlTextReader(reportXSD, fileXML); xtr.WhitespaceHandling = WhitespaceHandling.None; XmlValidatingReader xvr = new XmlValidatingReader(xtr); xvr.ValidationType = System.Xml.ValidationType.Schema; xvr.EntityHandling = System.Xml.EntityHandling.ExpandCharEntities; xmlDoc.Load(xvr); //xmlDoc.Load(fileXML); return(xmlDoc); } catch (Exception exc) { throw new ReportException(ErrorCode.InvalidXmlFile, "Errore nella convalida del del file XML: " + exc.Message); } //return null; }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: AnalyzeTimesheets <XML file>"); return; } try { // Code to read and validate XML goes here StreamReader stream = new StreamReader(args[0]); XmlTextReader reader = new XmlTextReader(stream); XmlSchemaCollection schemaColl = new XmlSchemaCollection(); schemaColl.Add(null, "Timesheet.xsd"); XmlValidatingReader valReader = new XmlValidatingReader(reader); valReader.ValidationType = ValidationType.Schema; // Q - types of validation? valReader.Schemas.Add(schemaColl); valReader.ValidationEventHandler += new ValidationEventHandler(valHandler); decimal hours = 0; while (valReader.Read()) { if (valReader.LocalName.Equals("ActivityName")) { Console.WriteLine("Activity: " + valReader.ReadString()); } if (valReader.LocalName.Equals("ActivityDuration")) { hours += Decimal.Parse(valReader.ReadString()); } } Console.WriteLine("File processed. Number of hours worked - {0}", hours); valReader.Close(); reader.Close(); stream.Close(); } catch (Exception e) { Console.WriteLine("Exception analyzing timesheet: " + e); } }
public void TestChoice() { string intSubset = "<!ELEMENT root (foo|bar)><!ELEMENT foo EMPTY><!ELEMENT bar EMPTY>"; string dtd = "<!DOCTYPE root [" + intSubset + "]>"; string xml = dtd + "<root><foo/><bar/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo try { dvr.Read(); // invalid element bar Assert.Fail("should be failed."); } catch (XmlSchemaException) { } xml = dtd + "<root><foo/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo dvr.Read(); // end root xml = dtd + "<root><bar/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // bar dvr.Read(); // end root xml = dtd + "<root><foo/>text.<bar/></root>"; dvr = PrepareXmlReader(xml); dvr.Read(); // DTD dvr.Read(); // root dvr.Read(); // foo try { dvr.Read(); // invalid text Assert.Fail("should be failed."); } catch (XmlSchemaException) { } }
public static void Main() { XmlValidatingReader reader = null; try { //Create the string to parse. string xmlFrag = "<book genre='novel' ISBN='1-861003-78' pubdate='1987'></book> "; //Create the XmlNamespaceManager. NameTable nt = new NameTable(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt); //Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); //Create the XmlValidatingReader . reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context); //Read the attributes on the root element. reader.MoveToContent(); if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Move the reader back to the node that owns the attribute. reader.MoveToElement(); } } finally { if (reader != null) { reader.Close(); } } }
public String Validar(string _xml, string _xsd) { Resultado = ""; if (!File.Exists(_xml) || !File.Exists(_xsd)) { return("NotFound"); } xml = _xml; //XmlReaderSettings settings = new XmlReaderSettings(); //settings.Schemas.Add("http://www.portalfiscal.inf.br/nfe", _xsd); //settings.ValidationType = ValidationType.Schema; //XmlReader reader = XmlReader.Create(_xml, settings); //XmlDocument document = new XmlDocument(); //document.Load(reader); //ValidationEventHandler eventHandler = new ValidationEventHandler(reader_ValidationEventHandler); //// the following call to Validate succeeds. //document.Validate(eventHandler); // Cria um novo XMLValidatingReader XmlValidatingReader reader = new XmlValidatingReader(new XmlTextReader(new StreamReader(_xml))); // Cria um schemacollection XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); //Adiciona o XSD e o namespace schemaCollection.Add("http://www.portalfiscal.inf.br/nfe", _xsd); // Adiciona o schema ao ValidatingReader reader.Schemas.Add(schemaCollection); //Evento que retorna a mensagem de validacao reader.ValidationEventHandler += new ValidationEventHandler(reader_ValidationEventHandler); //Percorre o XML while (reader.Read()) { } reader.Close(); //Fecha o arquivo. //O Resultado é preenchido no reader_ValidationEventHandler return(Resultado); }
public static void Main() { XmlSchemaCollection sc = new XmlSchemaCollection(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); sc.Add(null, "books.xsd"); 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 SchemaValidator(string xmlFile, string schemaFile) { XmlSchemaCollection myXmlSchemaCollection = new XmlSchemaCollection(); XmlTextReader xmlTextReader = new XmlTextReader(schemaFile); try { myXmlSchemaCollection.Add(XmlSchema.Read(xmlTextReader, null)); } finally { xmlTextReader.Close(); } // Validate the XML file with the schema XmlTextReader myXmlTextReader = new XmlTextReader(xmlFile); myXmlValidatingReader = new XmlValidatingReader(myXmlTextReader); myXmlValidatingReader.Schemas.Add(myXmlSchemaCollection); myXmlValidatingReader.ValidationType = ValidationType.Schema; }
public static void Main() { FileStream stream = new FileStream("../movies_list.xml", FileMode.Open); XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null); vr.Schemas.Add(null, "../moviesList.xsd"); vr.ValidationType = ValidationType.Schema; vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler); try { while (vr.Read()) { ; } } catch (Exception e) { } Console.WriteLine("Validation finished"); }
private void Validate(String filename, XmlSchemaCollection xsc) { XmlTextReader reader = null; XmlValidatingReader vreader = null; reader = new XmlTextReader(filename); vreader = new XmlValidatingReader(reader); vreader.Schemas.Add(xsc); vreader.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); try { while (vreader.Read()) { } } catch { Output.Text = "XML Document is not well-formed."; } vreader.Close(); }
public static void Main() { //Create the reader. XmlTextReader txtreader = new XmlTextReader("book4.xml"); XmlValidatingReader reader = new XmlValidatingReader(txtreader); reader.MoveToContent(); //Display each of the attribute nodes, including default attributes. while (reader.MoveToNextAttribute()) { if (reader.IsDefault) { Console.Write("(default attribute) "); } Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } //Close the reader. reader.Close(); }
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 }
public bool Load(string strFileName) { #pragma warning disable 0618 XmlTextReader rXmlTextReader; XmlValidatingReader rXmlValidatingReader; bool fRet; rXmlTextReader = new XmlTextReader(strFileName); rXmlTextReader.WhitespaceHandling = _eWhitespaceMode; rXmlTextReader.Namespaces = _fNamespaces; _eEncoding = rXmlTextReader.Encoding; rXmlValidatingReader = new XmlValidatingReader(rXmlTextReader); rXmlValidatingReader.ValidationType = _eValidationMode; rXmlValidatingReader.EntityHandling = _eEntityMode; #pragma warning restore 0618 if (_fValidationCallback) rXmlValidatingReader.ValidationEventHandler += new ValidationEventHandler(this.ValidationCallback); try { fRet = Load((XmlReader)rXmlValidatingReader); } catch (Exception e) { fRet = false; rXmlValidatingReader.Dispose(); rXmlTextReader.Dispose(); if (_strParseError == string.Empty) _strParseError = e.ToString(); if (_fThrow) throw (e); } rXmlValidatingReader.Dispose(); rXmlTextReader.Dispose(); return fRet; }
void RunTest (string subdir) { string basePath = @"xsd-test-suite" + SEP; XmlDocument doc = new XmlDocument (); if (noResolver) doc.XmlResolver = null; doc.Load (basePath + subdir + SEP + "tests-all.xml"); if (reportAsXml) { XmlReport = new XmlTextWriter (ReportWriter); XmlReport.Formatting = Formatting.Indented; XmlReport.WriteStartElement ("test-results"); } Console.WriteLine ("Started: " + DateTime.Now); foreach (XmlElement test in doc.SelectNodes ("/tests/test")) { // Test schema string schemaFile = test.SelectSingleNode ("@schema").InnerText; if (specificTarget != null && schemaFile.IndexOf (specificTarget) < 0) continue; if (schemaFile.Length > 2) schemaFile = schemaFile.Substring (2); if (verbose) Report (schemaFile, true, "compiling", ""); bool isValidSchema = test.SelectSingleNode ("@out_s").InnerText == "1"; XmlSchema schema = null; XmlTextReader sxr = null; try { sxr = new XmlTextReader (basePath + schemaFile); if (noResolver) sxr.XmlResolver = null; schema = XmlSchema.Read (sxr, null); schema.Compile (noValidate ? noValidateHandler : null, noResolver ? null : new XmlUrlResolver ()); if (!isValidSchema && !noValidate) { Report (schemaFile, true, "should fail", ""); continue; } if (reportSuccess) Report (schemaFile, true, "OK", ""); } catch (XmlSchemaException ex) { if (isValidSchema) Report (schemaFile, true, "should succeed", reportDetails ? ex.ToString () : ex.Message); else if (reportSuccess) Report (schemaFile, true, "OK", ""); continue; } catch (Exception ex) { if (stopOnError) throw; Report (schemaFile, true, "unexpected", reportDetails ? ex.ToString () : ex.Message); continue; } finally { if (sxr != null) sxr.Close (); } // Test instances string instanceFile = test.SelectSingleNode ("@instance").InnerText; if (instanceFile.Length == 0) continue; else if (instanceFile.StartsWith ("./")) instanceFile = instanceFile.Substring (2); if (verbose) Report (instanceFile, false, "reading ", ""); bool isValidInstance = test.SelectSingleNode ("@out_x").InnerText == "1"; XmlReader xvr = null; try { XmlTextReader ixtr = new XmlTextReader ( Path.Combine (basePath, instanceFile)); xvr = ixtr; #if NET_2_0 if (version2) { XmlReaderSettings settings = new XmlReaderSettings (); settings.ValidationType = ValidationType.Schema; if (noValidate) settings.ValidationEventHandler += noValidateHandler; if (noResolver) settings.Schemas.XmlResolver = null; settings.Schemas.Add (schema); if (noResolver) settings.XmlResolver = null; xvr = XmlReader.Create (ixtr, settings); } else { #endif XmlValidatingReader vr = new XmlValidatingReader (ixtr); if (noResolver) vr.XmlResolver = null; if (noValidate) vr.ValidationEventHandler += noValidateHandler; vr.Schemas.Add (schema); xvr = vr; #if NET_2_0 } #endif while (!xvr.EOF) xvr.Read (); if (!isValidInstance && !noValidate) Report (instanceFile, false, "should fail", ""); else if (reportSuccess) Report (instanceFile, false, "OK", ""); } catch (XmlSchemaException ex) { if (isValidInstance) Report (instanceFile, false, "should succeed", reportDetails ? ex.ToString () : ex.Message); else if (reportSuccess) Report (instanceFile, false, "OK", ""); } catch (Exception ex) { if (stopOnError) throw; Report (instanceFile, false, "unexpected", reportDetails ? ex.ToString () : ex.Message); } finally { if (xvr != null) xvr.Close (); } } if (reportAsXml) { XmlReport.WriteEndElement (); XmlReport.Flush (); } Console.WriteLine ("Finished: " + DateTime.Now); }
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; }
public void Load (string url, XmlResolver resolver) { XmlResolver res = resolver; if (res == null) res = new XmlUrlResolver (); Uri uri = res.ResolveUri (null, url); using (Stream s = res.GetEntity (uri, null, typeof (Stream)) as Stream) { XmlTextReader xtr = new XmlTextReader (uri.ToString (), s); xtr.XmlResolver = res; XmlValidatingReader xvr = new XmlValidatingReader (xtr); xvr.XmlResolver = res; xvr.ValidationType = ValidationType.None; Load (new XPathDocument (xvr, XmlSpace.Preserve).CreateNavigator (), resolver, null); } }
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); } } } }
private XmlReader GetXmlReader (string url) { XmlResolver res = new XmlUrlResolver (); Uri uri = res.ResolveUri (null, url); Stream s = res.GetEntity (uri, null, typeof (Stream)) as Stream; XmlTextReader xtr = new XmlTextReader (uri.ToString (), s); xtr.XmlResolver = res; XmlValidatingReader xvr = new XmlValidatingReader (xtr); xvr.XmlResolver = res; xvr.ValidationType = ValidationType.None; return xvr; }
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; }
static void Asymmetric (string filename) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.PreserveWhitespace = true; doc.Load (xvr); try { SignedXml s = null; if (filename.IndexOf ("enveloped") >= 0) s = new SignedXml (doc); else if (filename.IndexOf ("signature-big") >= 0) s = new SignedXml (doc); else s = new SignedXml (); XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", "http://www.w3.org/2000/09/xmldsig#"); s.LoadXml ((XmlElement) nodeList [0]); #if false // wanna dump? Console.WriteLine ("\n\nFilename : " + fi.Name); DumpSignedXml (s); #endif // MS doesn't extract the public key out of the certificates // http://www.dotnet247.com/247reference/a.aspx?u=http://www.kbalertz.com/Feedback_320602.aspx Mono.Security.X509.X509Certificate mx = null; foreach (KeyInfoClause kic in s.KeyInfo) { if (kic is KeyInfoX509Data) { KeyInfoX509Data kix = (kic as KeyInfoX509Data); if ((kix.Certificates != null) && (kix.Certificates.Count > 0)) { System.Security.Cryptography.X509Certificates.X509Certificate x509 = (System.Security.Cryptography.X509Certificates.X509Certificate) kix.Certificates [0]; byte[] data = x509.GetRawCertData (); mx = new Mono.Security.X509.X509Certificate (data); } } } // special cases // 1- Merlin's certificate resolution (manual) // 2- Phaos (because Fx doesn't support RetrievalMethod switch (shortName) { case "signature-keyname.xml": mx = LoadCertificate (GetPath (filename, "lugh.crt")); break; case "signature-retrievalmethod-rawx509crt.xml": mx = LoadCertificate (GetPath (filename, "balor.crt")); break; case "signature-x509-is.xml": mx = LoadCertificate (GetPath (filename, "macha.crt")); break; case "signature-x509-ski.xml": mx = LoadCertificate (GetPath (filename, "nemain.crt")); break; case "signature-x509-sn.xml": mx = LoadCertificate (GetPath (filename, "badb.crt")); break; // Phaos case "signature-big.xml": case "signature-rsa-manifest-x509-data-issuer-serial.xml": case "signature-rsa-manifest-x509-data-ski.xml": case "signature-rsa-manifest-x509-data-subject-name.xml": case "signature-rsa-detached-xslt-transform-retrieval-method.xml": mx = LoadCertificate (GetPath (filename, "rsa-cert.der")); break; case "signature-rsa-detached-xslt-transform-bad-retrieval-method.xml": mx = LoadCertificate (GetPath (filename, "dsa-ca-cert.der")); break; default: break; } bool result = false; if (mx != null) { if (mx.RSA != null) { result = s.CheckSignature (mx.RSA); } else if (mx.DSA != null) { result = s.CheckSignature (mx.DSA); } } else { // use a key existing in the document result = s.CheckSignature (); } if (result) { Console.WriteLine ("valid " + shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }
static void Symmetric (string filename, byte[] key) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.Load (xvr); try { XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement signature = (XmlElement) nodeList [0]; SignedXml s = new SignedXml (); s.LoadXml (signature); HMACSHA1 mac = new HMACSHA1 (key); if (s.CheckSignature (mac)) { Console.WriteLine ("valid {0}", shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }