Search Results

Search found 11 results on 1 pages for 'xmlschemaset'.

Page 1/1 | 1 

  • C# XmlSchemaSet - Resolving included schemas to enumerate attribute groups

    - by satixx
    Hi, I currently have a compiled XmlSchemaSet from which I get possible elements/attributes for each specific "parent" element defined in the schema. I have a single "master" xsd schema which includes another schema and uses attributeGroup references for some "common" elements. Here is a sample: (MasterSchema.xsd) <?xml version="1.0" encoding="utf-8"?> <xs:schema id="MasterSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="CommonNamespace.xsd" xmlns="CommonNamespace.xsd" xmlns:mstns="CommonNamespace.xsd" elementFormDefault="qualified" > <xs:include schemaLocation="SourceAttributeGroups.xsd"/> <xs:element name="Binding" minOccurs="0" maxOccurs="2"> <xs:complexType> <xs:attribute name="Name" type="xs:string"/> <xs:attributeGroup ref="BindingSourceAttributeGroup"/> </xs:complexType> </xs:element> </xs:schema> (SourceAttributeGroups.xsd) <?xml version="1.0" encoding="utf-8"?> <xs:schema id="SourceAttributeGroups" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="CommonNamespace.xsd" xmlns="CommonNamespace.xsd" xmlns:mstns="CommonNamespace.xsd" elementFormDefault="qualified" > <xs:attributeGroup id="BindingSourceAttributeGroup" name="BindingSourceAttributeGroup"> <xs:attribute name="Source"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Data"/> </xs:restriction> </xs:simpleType> </xs:attribute> <!-- When Source is None --> <xs:attribute name="Value" type="xs:string"/> <!-- Label --> <xs:attribute name="Label" type="xs:string"/> </attributeGroup> </xs:schema> I would like to create an XmlSchemaSet in C# which would resolve, compile and "merge" every references of the MasterSchema so it would finaly look like this: (MasterSchema.xsd) <?xml version="1.0" encoding="utf-8"?> <xs:schema id="MasterSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="CommonNamespace.xsd" xmlns="CommonNamespace.xsd" xmlns:mstns="CommonNamespace.xsd" elementFormDefault="qualified" > <xs:include schemaLocation="SourceAttributeGroups.xsd"/> <xs:element name="Binding" minOccurs="0" maxOccurs="2"> <xs:complexType> <xs:attribute name="Name" type="xs:string"/> <xs:attribute name="Source"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Data"/> </xs:restriction> </xs:simpleType> </xs:attribute> <!-- When Source is None --> <xs:attribute name="Value" type="xs:string"/> <!-- Label --> <xs:attribute name="Label" type="xs:string"/> </xs:complexType> </xs:element> </xs:schema> This way, I could traverse each XmlSchemaParticle of the compiled schema to get every single attribute for a specific element, even when its attributes are defined in an external schema. At the moment, when I get the possible attributes for a "Binding" element, I only get the "Name" attribute since it is originally defined in the "master" schema. What would be the possible solutions to this problem? Thanks! Satixx

    Read the article

  • How to compile a schema that uses a DataSet (xs:schema)?

    - by Yaron Naveh
    I have created the simplest web service in c#: public void AddData(DataSet ds) The generated schema (Wsdl) looks like this: <s:schema xmlns:s="http://www.w3.org/2001/XMLSchema"> ... <s:element ref="s:schema" /> ... </s:schema> Note the schema does not contain any import/include elements. I am trying to load this schema to a c# System.Xml.XmlSchema and add it to System.Xml.XmlSchemaSet: var set = new XmlSchemaSet(); var fs = new FileStream(@"c:\temp\schema.xsd", FileMode.Open); var s = XmlSchema.Read(fs, null); set.Add(s); set.Compile(); The last line throws this exception: The 'http://www.w3.org/2001/XMLSchema:schema' element is not declared. It kind of makes sense: The schema generated by .Net uses the "s:schema" type which is declared in a schema which is not imported. Why does .Net create a non valid schema? How to compile the schema anyway? Whay I did is download the schema in http://www.w3.org/2001/XMLSchema and added it to the XmlSchemaSet also. This did not work since that online schema contains DTD definition. I had to manually remove it and now all works. Does this make sense or am I missing something?

    Read the article

  • xmldocument and nested schemas

    - by Stuart
    Using c# and .net 3.5 I'm trying to validate an xml document against a schema that has includes. The schemas and there includes are as below Schema1.xsd - include another.xsd another.xsd - include base.xsd When i try to add the Schema1.xsd to the XmlDocument i get the following error. Type 'YesNoType' is not declared or is not a simple type. I believe i'm getting this error because the base.xsd file is not being included when i load the Schema1.xsd schema. I'm trying to use the XmlSchemaSet class and I'm setting the XmlResolver uri to the location of the schemas. NOTE : All schemas live under the same directory E:\Dev\Main\XmlSchemas Here is the code string schemaPath = "E:\\Dev\\Main\\XmlSchemas"; XmlDocument xmlDocSchema = new XmlDocument(); XmlSchemaSet s = new XmlSchemaSet(); XmlUrlResolver resolver = new XmlUrlResolver(); Uri baseUri = new Uri(schemaPath); resolver.ResolveUri(null, schemaPath); s.XmlResolver = resolver; s.Add(null, XmlReader.Create(new System.IO.StreamReader(schemaPath + "\\Schema1.xsd"), new XmlReaderSettings { ValidationType = ValidationType.Schema, XmlResolver = resolver }, new Uri(schemaPath).ToString())); xmlDocSchema.Schemas.Add(s); ValidationEventHandler valEventHandler = new ValidationEventHandler (ValidateNinoDobEvent); try { xmlDocSchema.LoadXml(xml); xmlDocSchema.Validate(valEventHandler); } catch (XmlSchemaValidationException xmlValidationError) { // need to interogate the Validation Exception, for possible further // processing. string message = xmlValidationError.Message; return false; } Can anyone point me in the right direction regarding validating an xmldocument against a schema with nested includes.

    Read the article

  • XmlDocument.Load() throws XmlSchemaValidationException

    - by Praetorian
    Hi, I'm trying to validate an XML document against a schema (which is embedded in my program as a resource). I got everything to work, so I tried to test for errors by adding a second sibling node in the XML at a location where the schema specifies maxOccurs="1". The problem is that my ValidationEventHandler is never getting called, also XmlDocument.Load() is throwing an XmlSchemaValidationException exception when I'd expected XmlDocument.Validate() to do that. This is the code I have: private void ValidateUserData( string xmlPath ) { var resInfo = Application.GetResourceStream( new Uri( @"MySchema.xsd", UriKind.Relative ) ); var schema = XmlSchema.Read( resInfo.Stream, SchemaValidationCallBack ); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add( schema ); schemaSet.ValidationEventHandler += SchemaValidationCallBack; XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas = schemaSet; settings.ValidationType = ValidationType.Schema; XmlDocument doc = new XmlDocument(); using( XmlReader reader = XmlReader.Create( xmlPath, settings ) ) { doc.Load( reader ); // <-- This line throws an exception if XML is ill-formed reader.Close(); } doc.Validate( SchemaValidationCallBack );// <-- This is never reached } private void SchemaValidationCallBack( object sender, ValidationEventArgs e ) { Console.WriteLine( "SchemaValidationCallBack: " + e.Message ); } How do I get the callback to be called so I can handle validation errors? Thanks for your help!

    Read the article

  • Validate a XDocument against schema without the ValidationEventHandler (for use in a HTTP handler)

    - by Vaibhav Garg
    Hi everyone, (I am new to Schema validation) Regarding the following method, System.Xml.Schema.Extensions.Validate( ByVal source As System.Xml.Linq.XDocument, ByVal schemas As System.Xml.Schema.XmlSchemaSet, ByVal validationEventHandler As System.Xml.Schema.ValidationEventHandler, ByVal addSchemaInfo As Boolean) I am using it as follows inside a IHttpHandler - Try Dim xsd As XmlReader = XmlReader.Create(context.Server.MapPath("~/App_Data/MySchema.xsd")) Dim schemas As New XmlSchemaSet() : schemas.Add("myNameSpace", xsd) : xsd.Close() myXDoxumentOdj.Validate(schemas, Function(s As Object, e As ValidationEventArgs) SchemaError(s, e, context), True) Catch ex1 As Threading.ThreadAbortException 'manage schema error' Return Catch ex As Exception 'manage other errors' End Try The handler- Function SchemaError(ByVal s As Object, ByVal e As ValidationEventArgs, ByVal c As HttpContext) As Object If c Is Nothing Then c = HttpContext.Current If c IsNot Nothing Then HttpContext.Current.Response.Write(e.Message) HttpContext.Current.Response.End() End If Return New Object() End Function This is working fine for me at present but looks very weak. I do get errors when I feed it bad XML. But i want to implement it in a more elegant way. This looks like it would break for large XML etc. Is there some way to validate without the handler so that I get the document validated in one go and then deal with errors? To me it looks Async such that the call to Validate() would pass and some non deterministic time later the handler would get called with the result/errors. Is that right? Thanks and sorry for any goofy mistakes :).

    Read the article

  • NHibernate: Collection was modified; enumeration operation may not execute

    - by Daoming Yang
    Hi All, I'm currently struggling with this "Collection was modified; enumeration operation may not execute" issue. I have searched about this error message, and it's all related to the foreach statement. I do have the some foreach statements, but they are just simply representing the data. I did not using any remove or add inside the foreach statement. NOTE: The error randomly happens (about 4-5 times a day). The application is the MVC website. There are about 5 users operate this applications (about 150 orders a day). Could it be some another users modified the collection, and then occur this error? I have log4net setup and the settings can be found here Make sure that the controller has a parameterless public constructor I do have parameterless public constructor in AdminProductController Does anyone know why this happen and how to resolve this issue? A friend (Oskar) mentioned that "Theory: Maybe the problem is that your configuration and session factory is initialized on the first request after application restart. If a second request comes in before the first request is finished, maybe it will also try to initialize and then triggering this problem somehow." Many thanks. Daoming Here is the error message: System.InvalidOperationException Collection was modified; enumeration operation may not execute. System.InvalidOperationException: An error occurred when trying to create a controller of type 'WebController.Controllers.Admin.AdminProductController'. Make sure that the controller has a parameterless public constructor. --- System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --- NHibernate.MappingException: Could not configure datastore from input stream DomainModel.Entities.Mappings.OrderProductVariant.hbm.xml --- System.InvalidOperationException: Collection was modified; enumeration operation may not execute. at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() at System.Xml.Schema.XmlSchemaSet.AddSchemaToSet(XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema) at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema) at NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) --- End of inner exception stack trace --- at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly) at DomainModel.RepositoryBase..ctor() at WebController.Controllers._baseController..ctor() at WebController.Controllers.Admin.AdminProductController..ctor() at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) --- End of inner exception stack trace --- at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) at System.Activator.CreateInstance(Type type, Boolean nonPublic) at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) --- End of inner exception stack trace --- at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) UPDATE CODE: In my Global.asax.cs, I'm doing this: protected void Application_BeginRequest(object sender, EventArgs e) { ManagedWebSessionContext.Bind(HttpContext.Current, SessionManager.SessionFactory.OpenSession()); } protected void Application_EndRequest(object sender, EventArgs e) { ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory); if (session != null) { try { if (session.Transaction != null && session.Transaction.IsActive) { session.Transaction.Rollback(); } else { session.Flush(); } } finally { session.Close(); } } } In the SessionManager class, I'm doing: public class SessionManager { private readonly ISessionFactory sessionFactory; public static ISessionFactory SessionFactory { get { return Instance.sessionFactory; } } private ISessionFactory GetSessionFactory() { return sessionFactory; } public static SessionManager Instance { get { return NestedSessionManager.sessionManager; } } public static ISession OpenSession() { return Instance.GetSessionFactory().OpenSession(); } public static ISession CurrentSession { get { return Instance.GetSessionFactory().GetCurrentSession(); } } private SessionManager() { Configuration config = new Configuration().Configure(); config.AddAssembly(Assembly.GetExecutingAssembly()); sessionFactory = config.BuildSessionFactory(); } class NestedSessionManager { internal static readonly SessionManager sessionManager = new SessionManager(); } } In the Repository, I'm doing this: public IEnumerable<User> GetAll() { ICriteria criteria = SessionManager.CurrentSession.CreateCriteria(typeof(User)); return criteria.List<User>(); } In the Controller, I'm doing this: public class UserController : _baseController { IUserRoleRepository _userRoleRepository; internal static readonly ILogger log = LogManager.GetLogger(typeof(UserController)); public UserController() { _userRoleRepository = new UserRoleRepository(); } public ActionResult UserList() { var myList = _usersRepository.GetAll(); return View(myList); } }

    Read the article

  • Getting started with XSD validation with C#

    - by Rosarch
    Here is my first attempt at validating XML with XSD. The XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd"> <levelVariant> <filePath>SampleVariant</filePath> </levelVariant> <levelVariant> <filePath>LegendaryMode</filePath> </levelVariant> <levelVariant> <filePath>AmazingMode</filePath> </levelVariant> </config> The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="config"> <xs:complexType> <xs:sequence> <xs:element name="levelVariant"> <xs:complexType> <xs:sequence> <xs:element name="filePath" type="xs:anyURI"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists? The validation code in C#: public void SetURI(string uri) { XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml"); // begin confusion string schemaURI = toValidate.Attributes("xmlns").First().ToString() + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", XmlReader.Create( SOMETHING )); XDocument toValidateDoc = new XDocument(toValidate); toValidateDoc.Validate(schemas, null); // end confusion root = toValidate; } Any illumination would be appreciated.

    Read the article

  • Getting started with XSD validation with .NET

    - by Rosarch
    Here is my first attempt at validating XML with XSD. The XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <config xmlns="Schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="config.xsd"> <levelVariant> <filePath>SampleVariant</filePath> </levelVariant> <levelVariant> <filePath>LegendaryMode</filePath> </levelVariant> <levelVariant> <filePath>AmazingMode</filePath> </levelVariant> </config> The XSD, located in "Schemas/config.xsd" relative to the XML file to be validated: <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"> <xs:element name="config"> <xs:complexType> <xs:sequence> <xs:element name="levelVariant"> <xs:complexType> <xs:sequence> <xs:element name="filePath" type="xs:anyURI"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Right now, I just want to validate the XML file precisely as it appears currently. Once I understand this better, I'll expand more. Do I really need so many lines for something as simple as the XML file as it currently exists? The validation code in C#: public void SetURI(string uri) { XElement toValidate = XElement.Load(Path.Combine(PATH_TO_DATA_DIR, uri) + ".xml"); // begin confusion // exception here string schemaURI = toValidate.Attributes("xmlns").First().ToString() + toValidate.Attributes("xsi:noNamespaceSchemaLocation").First().ToString(); XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add(null, schemaURI); XDocument toValidateDoc = new XDocument(toValidate); toValidateDoc.Validate(schemas, null); // end confusion root = toValidate; } Running the above code gives this exception: The ':' character, hexadecimal value 0x3A, cannot be included in a name. Any illumination would be appreciated.

    Read the article

  • VB.Net Validate an xml against a schema (strange problem)

    - by Apeksha
    I have written a small XML validator, that takes in an XML file and an XML schema and validates the XML files against that schema. It works well, except for an XML file, with this content: <?xml version="1.0" encoding="utf-8"?> <xc:program xmlns:xc="http:\\www.something.com\Schema\XC10" xc:version="4.0.22.0" > <xc:namespaceDecls> <xc:namespaceDecl xc:namespaceDeclURI="urn:swift:xsd:abc"> <xc:namespaceDeclPrefix>n</xc:namespaceDeclPrefix> </xc:namespaceDecl> </xc:namespaceDecls> </xc:program> I tried to validate this XML file against a bunch of different schemas. No matter which schema I select, this XML file comes out as valid. What is it that I am missing? Here is the relevant piece of code: 'Create a schema cache and add the given schema to it. Dim schemaCache As New Schema.XmlSchemaSet schemaCache.Add(targetNamespace, schemaFilename) 'Create an XML DOMDocument object. Dim xmlDom As New XmlDocument 'Assign the schema cache to the DOM document. 'schemas collection. xmlDom.Schemas = schemaCache 'Load selected file as the DOM document. xmlDom.Load(xmlFilename) xmlDom.Validate(AddressOf ValidationCallBack)

    Read the article

  • How to change XmlSchemaElement.SchemaType (or: difference between SchemaType and ElementSchemaType)

    - by Gregor
    Hey, I'm working on a XML Editor which gets all his information from the corresponding XSD file. To work with the XSD files I use the System.Xml.Schema Namespace (XmlSchema*). Because of an 'xsi:type' attribute in the XML I've to change the XmlSchemaType of an XmlSchemaElement. Until now I use in my code the 'ElementSchemaType' property of 'XmlSchemaElement'. The nice thing about it: it's read only. There is also in 'XmlSchemaElement' an 'SchemaType' property which is not read only, but always null (yes, XmlSchema and XmlSchemaSet are compiled). So how can I change the type of the 'XmlSchemaElement'? Or, also the same question: What is the diffrence between this two porperties? Some technical data: C#, .NET 3.5 The MSDN documentation is nearly the same for both: SchemaType Documentation: Gets or sets the type of the element. This can either be a complex type or a simple type. ElementSchemaType Documentation: Gets an XmlSchemaType object representing the type of the element based on the SchemaType or SchemaTypeName values of the element.

    Read the article

  • WCF: WSDL-first approach: Problems with generating fault types

    - by Juri
    Hi, I'm currently in the process of creating a WCF webservice which should be compatible with WS-I Basic Profile 1.1. I'm using a wsdl-first approach (actually for the first time), defining first the xsd for the complex types, the WSDL and then using svcutil.exe for generating the according server as well as client-side interfaces/proxies. So far everything works fine. Then I decided to add a fault to my WSDL. Regenerating with svcutil succeeded, but then I noticed that my generated fault doesn't have the properties I defined in my xsd file (which is imported by my WSDL). Fault XSD definition <?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://product.mycompany.com/groupsfault_v1.xsd" xmlns:tns="http://product.mycompany.com/groupsfault_v1.xsd"> <complexType name="groupsFault"> <sequence> <element name="code" type="int"/> <element name="message" type="string"/> </sequence> </complexType> </schema> Generated .Net fault object [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")] [System.Xml.Serialization.XmlSchemaProviderAttribute("ExportSchema")] [System.Xml.Serialization.XmlRootAttribute(IsNullable=false)] public partial class groupFault : object, System.Xml.Serialization.IXmlSerializable { private System.Xml.XmlNode[] nodesField; private static System.Xml.XmlQualifiedName typeName = new System.Xml.XmlQualifiedName("groupFault", "http://sicp.services.siag.it/groups_v1.wsdl"); public System.Xml.XmlNode[] Nodes { get { return this.nodesField; } set { this.nodesField = value; } } public void ReadXml(System.Xml.XmlReader reader) { this.nodesField = System.Runtime.Serialization.XmlSerializableServices.ReadNodes(reader); } public void WriteXml(System.Xml.XmlWriter writer) { System.Runtime.Serialization.XmlSerializableServices.WriteNodes(writer, this.Nodes); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas) { System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName); return typeName; } } Is this ok?? I'd expect to have an object created that contains properties for "code" and "message" s.t. you can then throw it by using something like ... throw new FaultException<groupFault>(new groupFault { code=100, message="error" }); ... (sorry for the lower-case type definitions, but this is generated code from the WSDL) Why doesn't the svcutil.exe generate those properties?? Some sources on the web suggested to add the /useSerializerForFaults option. I tried it, it doesn't work giving me an exception that the fault type is missing on the wsdl:portType declaration. Validation with several other tools succeeded however. Any help is VERY appreciated :) thx

    Read the article

1