public void Attach(XmlDocument doc, Uri baseUri) { Detach(); this.document = doc; if (doc.DocumentType == null) { return; } DTDParser dtp = new DTDParser(); bool hasInternalSubset = doc.DocumentType.InternalSubset != null; bool internalSubsetOnly = doc.DocumentType.SystemId == null; if (baseUri == null && !doc.BaseURI.Equals("")) { baseUri = new Uri(doc.BaseURI); } // TODO: H: shouldn't this use the doc's resolver? CustomXmlResolver cxr = new CustomXmlResolver(baseUri); dtp.XmlResolver = cxr; if (hasInternalSubset) { InputSource ii = new InputSource(doc.DocumentType.InternalSubset); documentType = dtp.parseInternalSubset(ii, internalSubsetOnly); } if (!internalSubsetOnly) { Uri doctypeUri = cxr.ResolveUri(baseUri, doc.DocumentType.SystemId); InputSource i = new InputSource(doctypeUri); if (hasInternalSubset) { documentType = dtp.parseExternalSubset(i); } else { documentType = dtp.parseExternalSubset(i, true); } } validationEngine = new ValidationEngine(documentType, this); quickFixer = new QuickFixer(documentType); GetAllIdAndIdRefs(); ValidateAllIdAndIdRefs(); document.NodeChanging += new XmlNodeChangedEventHandler(NodeChanging); document.NodeChanged += new XmlNodeChangedEventHandler(NodeChanged); document.NodeInserted += new XmlNodeChangedEventHandler(NodeInserted); document.NodeRemoved += new XmlNodeChangedEventHandler(NodeRemoved); }
private static CustomXmlResolver CreateSchematronResolver(List <ImplementationGuideFile> schHelperFiles) { CustomXmlResolver resolver = new CustomXmlResolver(); resolver.AddStoredFile("skeleton1-5.xsl", GetResource("Trifolia.ValidationService.Schematron.skeleton1-5.xsl")); resolver.AddStoredFile("RNG2Schtrn.xsl", GetResource("Trifolia.ValidationService.Schematron.RNG2Schtrn.xsl")); resolver.AddStoredFile("XSD2Schtrn.xsl", GetResource("Trifolia.ValidationService.Schematron.XSD2Schtrn.xsl")); resolver.AddStoredFile("iso_schematron_skeleton.xsl", GetResource("Trifolia.ValidationService.Schematron.iso_schematron_skeleton.xsl")); // Add schematron helper files to resolver schHelperFiles.ForEach(y => resolver.AddStoredFile(y.FileName, y.GetLatestData().Data)); return(resolver); }
public void Attach(XmlDocument doc, Uri baseUri) { Detach(); this.document=doc; if ( doc.DocumentType == null ) return; DTDParser dtp=new DTDParser(); bool hasInternalSubset=doc.DocumentType.InternalSubset != null; bool internalSubsetOnly=doc.DocumentType.SystemId == null; if ( baseUri == null && !doc.BaseURI.Equals("") ) baseUri=new Uri(doc.BaseURI); // TODO: H: shouldn't this use the doc's resolver? CustomXmlResolver cxr=new CustomXmlResolver(baseUri); dtp.XmlResolver=cxr; if ( hasInternalSubset ) { InputSource ii=new InputSource(doc.DocumentType.InternalSubset); documentType=dtp.parseInternalSubset(ii, internalSubsetOnly); } if ( !internalSubsetOnly ) { Uri doctypeUri=cxr.ResolveUri(baseUri, doc.DocumentType.SystemId); InputSource i=new InputSource(doctypeUri); if ( hasInternalSubset ) documentType=dtp.parseExternalSubset(i); else documentType=dtp.parseExternalSubset(i, true); } validationEngine=new ValidationEngine(documentType, this); quickFixer=new QuickFixer(documentType); GetAllIdAndIdRefs(); ValidateAllIdAndIdRefs(); document.NodeChanging+=new XmlNodeChangedEventHandler(NodeChanging); document.NodeChanged+=new XmlNodeChangedEventHandler(NodeChanged); document.NodeInserted+=new XmlNodeChangedEventHandler(NodeInserted); document.NodeRemoved+=new XmlNodeChangedEventHandler(NodeRemoved); }
//private void ABC() //{ // List<string> l = new List<string>(); // foreach (var type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes().OrderBy(item => item.Name)) // { // List<string> l1 = new List<string>(); // Type tmp = type; // while (tmp != null) // { // if (tmp == typeof(Ifc4.IfcProduct)) // { // if (!type.IsAbstract) // l.Add(type.FullName); // } // tmp = tmp.BaseType; // } // } // l.Sort(); // foreach (var ll in l) // { // System.Diagnostics.Debug.WriteLine(ll); // } //} public bool Validate(string xmlFullName, bool useLocalSchemaFiles) { try { _ErrorCounter = 0; // reset counter _WarningCounter = 0; // reset counter //WriteLog(String.Empty.PadRight(_NumberOfSeparator, '*')); WriteLog("Start schema validation..."); if (String.IsNullOrEmpty(xmlFullName)) { WriteLog("No open file found!"); return(false); } WriteLog(String.Format("IfcXml File: '{0}'", xmlFullName)); string schemaXsdFullName = GetSchemaXsdFullName("ifcXML4.xsd"); WriteLog(String.Format("Xsd File: {0}", schemaXsdFullName)); XmlReaderSettings settings = new XmlReaderSettings(); if (useLocalSchemaFiles) { // externe XML-Ressourcen aufösen Uri uri = new Uri(AssemblyDirectoryFullName + "\\"); CustomXmlResolver resolver = new CustomXmlResolver(uri); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; resolver.UriMap.Add(@"http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd", "ifcXML4.xsd"); WriteLog(String.Format("Mapping path: '{0}'", uri.AbsolutePath)); foreach (var c in resolver.UriMap) { WriteLog(String.Format("Map '{0}' to local file '{1}'", c.Key, c.Value)); } settings.Schemas.XmlResolver = resolver; } //string targetNamespace = "http://www.buildingsmart-tech.org/ifcXML/IFC4/final"; //Uri schemaUri = new Uri("http://www.buildingsmart-tech.org/ifcXML/IFC4/final/ifcXML4.xsd"); //string schemaFullName = schemaUri.AbsoluteUri; //namespaces.Add("ifc", "http://www.buildingsmart-tech.org/ifcXML/IFC4/final"); //XmlSchemaSet schemaSet = new XmlSchemaSet(); //schemaSet.Add(targetNamespace, "ifcXML4.xsd"); //foreach (XmlSchema schema in schemaSet.Schemas("http://www.buildingsmart-tech.org/ifcXML/IFC4/final")) //{ // schema.Write(Console.Out); //} //settings.Schemas.Add(null, "ifcXML4.xsd"); settings.Schemas.Add(null, schemaXsdFullName); //settings.Schemas.Add(targetNamespace, schemaFullName); settings.ValidationType = ValidationType.Schema; //settings.DtdProcessing= DtdProcessing.Ignore settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; //settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); string source = System.IO.File.ReadAllText(xmlFullName); using (MemoryStream stream = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write(source); writer.Flush(); stream.Position = 0; using (XmlReader reader = XmlReader.Create(stream, settings)) { while (reader.Read()) { } } } } return(_ErrorCounter == 0); } catch (Exception exc) { WriteLog(""); WriteLog("Fatal error: Cannot validate file."); WriteLog(exc.Message); WriteLog(""); return(false); } finally { WriteLog(String.Format("{0} Error(s); {1} Warnings(s)", _ErrorCounter, _WarningCounter)); WriteLog("Validation finished."); WriteLog(String.Empty.PadRight(_NumberOfSeparator, '*')); if (Info != null) { Ifc4.EventArgs.MessageLogType result; if (_ErrorCounter > 0) { result = Ifc4.EventArgs.MessageLogType.Error; } else { result = Ifc4.EventArgs.MessageLogType.Valid; if (_WarningCounter > 0) { result |= Ifc4.EventArgs.MessageLogType.Warning; } } m_MessageLoggedEventArgs.Type = result; Info(this, m_MessageLoggedEventArgs); } } }
public void ValidCases(object param0, object param1, object param2, object param3, object param4, object param5) { string xslFile = FullFilePath(param0 as string); string xmlFile = FullFilePath(param1 as string); string baseLineFile = @"\baseline\" + param2 as string; bool expectedResult = (bool)param4; bool actualResult = false; XmlReader xmlReader = XmlReader.Create(xmlFile); //Let's select randomly how to create navigator IXPathNavigable navigator = null; Random randGenerator = new Random((int)DateTime.Now.Ticks); switch (randGenerator.Next(2)) { case 0: _output.WriteLine("Using XmlDocument.CreateNavigator()"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlFile); navigator = xmlDoc.CreateNavigator(); break; case 1: _output.WriteLine("Using XPathDocument.CreateNavigator()"); XPathDocument xpathDoc; using (XmlReader reader = XmlReader.Create(xmlFile)) { xpathDoc = new XPathDocument(reader); navigator = xpathDoc.CreateNavigator(); } break; default: break; } XmlResolver resolver = null; switch (param3 as string) { case "NullResolver": break; case "XmlUrlResolver": resolver = new XmlUrlResolver(); break; case "CustomXmlResolver": resolver = new CustomXmlResolver(Path.GetFullPath(Path.Combine(FilePathUtil.GetTestDataPath(), @"XsltApiV2\"))); break; default: break; } try { XslCompiledTransform localXslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(true, true); using (XmlReader xslReader = XmlReader.Create(xslFile)) localXslt.Load(xslReader, settings, resolver); using (XmlWriter writer = XmlWriter.Create("outputFile.txt")) { if (param5 as string == "XmlReader") localXslt.Transform(xmlReader, null, writer, resolver); else localXslt.Transform(navigator, null, writer, resolver); } VerifyResult(baseLineFile, "outputFile.txt"); actualResult = true; } catch (Exception ex) { _output.WriteLine(ex.Message); actualResult = false; } if (actualResult != expectedResult) Assert.True(false); return; }
/// <summary> /// Loads a document from a file path or URL. /// </summary> /// <param name="uriString">The file path or URL to load.</param> /// <param name="allowWellFormed">Indicates whether to allow well-formed but invalid documents.</param> /// <param name="isValid">[out] Set to true if document is valid.</param> /// <returns>The XmlDocument that was loaded, or null if unsuccessful.</returns> /// <remarks> /// <para>If allowWellFormed is true, a message box is displayed when an /// invalid document is read, asking if the user wants to attempt to load /// the document as well-formed.</para> /// </remarks> public static XmlDocument LoadDocument(string uriString, bool allowWellFormed, out bool isValid) { XmlDocument doc=new XmlDocument(); isValid=true; Uri uri=new Uri(uriString); XmlTextReader xtr=new XmlTextReader(uriString); XmlResolver xr=new CustomXmlResolver(uri); xtr.XmlResolver=xr; doc.XmlResolver=xr; try { XmlValidatingReader xvr=new XmlValidatingReader(xtr); xvr.EntityHandling=EntityHandling.ExpandCharEntities; doc.Load(xvr); return doc; } catch ( XmlSchemaException e ) { isValid=false; string msg=string.Format("The document is not valid. Do you want to attempt to load the document as well-formed?\n{0}", e.Message); DialogResult res=MessageBox.Show(msg, "Open File", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if ( res != DialogResult.OK ) throw; } catch ( FileNotFoundException e ) { Uri errorFile=new Uri(e.FileName); if ( errorFile.Equals(uri) ) throw; // TODO: M: refactor (repeat of above) - but is different isValid=false; string msg=string.Format("One or more files that this document depends on could not be found. Do you want to attempt to load the document as well-formed?\n{0}", e.Message); DialogResult res=MessageBox.Show(msg, "Open File", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if ( res != DialogResult.OK ) throw; xr=null; // do not attempt to resolve entities } finally { xtr.Close(); } try { xtr=new XmlTextReader(uriString); xtr.XmlResolver=xr; doc.Load(xtr); return doc; } finally { xtr.Close(); } }