Search Results

Search found 15873 results on 635 pages for 'xml deserialization'.

Page 1/635 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • XML Schema: Namespace issues when importing shared elements

    - by netzwerg
    When trying to import shared definitions from a XML Schema, I can properly reference shared types, but referencing shared elements causes validation errors. This is the schema that imports the shared definitions (example.xsd): <?xml version="1.0" encoding="UTF-8"?> <xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:shared="http://shared.com"> <xs:import namespace="http://shared.com" schemaLocation="shared.xsd"/> <xs:element name="example"> <xs:complexType> <xs:sequence> <xs:element ref="importedElement"/> <xs:element ref="importedType"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="importedElement"> <xs:complexType> <xs:sequence> <xs:element ref="shared:fooElement"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="importedType"> <xs:complexType> <xs:sequence> <xs:element name="bar" type="shared:barType"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> These are the shared definitions (shared.xsd): <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://shared.com" targetNamespace="http://shared.com"> <xs:element name="fooElement"> <xs:simpleType> <xs:restriction base="xs:integer"/> </xs:simpleType> </xs:element> <xs:simpleType name="barType"> <xs:restriction base="xs:integer"/> </xs:simpleType> </xs:schema> Now consider this XML instance: <?xml version="1.0"?> <example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="example.xsd"> <importedElement> <fooElement>42</fooElement> </importedElement> <importedType> <bar>42</bar> </importedType> </example> When validated, the "importedType" works perfectly fine, but the "importedElement" gives the following error: Invalid content was found starting with element 'fooElement'. One of '{"http://shared.com":fooElement}' is expected I would guess that my troubles are related to namespace issues (hence the somehow misleading "got fooElement but was expecting fooElement") -- any hints on what's wrong here?

    Read the article

  • XML Deserialization in VB/VBA

    - by oharab
    I have a set of VBA classes in an MS Access database. I have an xml string with data I want to create new classes with. Other than setting each property individually, is there an easy way to deserialize the XML into my object? I've seen the code using the TypeLib library Public Sub ISerializable_Deserialize(xml As IXMLDOMNode) Dim tTLI As TLIApplication Dim tInvoke As InvokeKinds Dim tName As String Dim tMem As MemberInfo tInvoke = VbLet For Each tMem In TLI.ClassInfoFromObject(Me).Members tName = LCase(tMem.Name) CallByName Me, tMem.Name, VbLet, xml.Attributes.getNamedItem(tName).Text Next tMem End Sub but this doesn't seem to work with the standard class modules. I get a 429 error: ActiveX Component Cannot Be Created Can anyone else help me out? I'd rather not have to set each propery by hand if I can help it, some of these classes are huge!

    Read the article

  • Alternative for namespaces in xml

    - by mridul4c
    I have a web-service which gives a xml feed for number of clients of us, our clients consumes the xml in different types of devices. In our XML we have some namespaces also. But one of our clients can't detect namespaces because of some limitation at their end. But I can't provide a new xml for him as well. Please suggest me something so that I can satisfy the needs of namespaces without using that, so that i can change my xml to be usable by all of them. Thanks in advance.

    Read the article

  • XML deserializer (Iserialzable)

    - by user311130
    Hey everybody, I have a class in c# that implements Iserialzable. I'm using a XMLSerializer that produces a XML from instance of that class. I get the following XML: <?xml version="1.0"?> <Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SessionConfiguration> <RemoteMachineName>HV-BENDA</RemoteMachineName> </SessionConfiguration> <SessionsCredentialsList> <CredentialsItem> <User>test0</User> <Password>Pa$$word1</Password> </CredentialsItem> <CredentialsItem> <User>test1</User> <Password>Pa$$word1</Password> </CredentialsItem> <CredentialsItem> <User>test2</User> <Password>Pa$$word1</Password> </CredentialsItem> <CredentialsItem> <User>test3</User> <Password>Pa$$word1</Password> </CredentialsItem> <CredentialsItem> <User>test4</User> <Password>Pa$$word1</Password> </CredentialsItem> </SessionsCredentialsList> <TIME_OUT /> <LOCAL_USERS_NUM>5</LOCAL_USERS_NUM> </Configuration> At some later point in the code I use a XMLSerializer again to deserial that XML document. and I get the following error: {"There is an error in XML document (1, 1)."} Inner exception: {"Data at the root level is invalid. Line 1, position 1."} Do someone knows wat could be the problem? All the best

    Read the article

  • Use XQuery to Access XML in Emacs

    - by Gregory Burd
    There you are working on a multi-MB/GB/TB XML document or set of documents, you want to be able to quickly query the content but you don't want to load the XML into a full-blown XML database, the time spent setting things up is simply too expensive. Why not combine a great open source editor, Emacs, and a great XML XQuery engine, Berkeley DB XML? That is exactly what Donnie Cameron did. Give it a try.

    Read the article

  • Validating an XML document fragment against XML schema

    - by shylent
    Terribly sorry if I've failed to find a duplicate of this question. I have a certain document with a well-defined document structure. I am expressing that structure through an XML schema. That data structure is operated upon by a RESTful service, so various nodes and combinations of nodes (not the whole document, but fragments of it) are exposed as "resources". Naturally, I am doing my own validation of the actual data, but it makes sense to validate the incoming/outgoing data against the schema as well (before the fine-grained validation of the data). What I don't quite grasp is how to validate document fragments given the schema definition. Let me illustrate: Imagine, the example document structure is: <doc-root> <el name="foo"/> <el name="bar"/> </doc-root> Rather a trivial data structure. The schema goes something like this: <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="doc-root"> <xsd:complexType> <xsd:sequence> <xsd:element name="el" type="myCustomType" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:complexType name="myCustomType"> <xsd:attribute name="name" use="required" /> </xsd:complexType> </xsd:schema> Now, imagine, I've just received a PUT request to update an 'el' object. Naturally, I would receive not the full document or not any xml, starting with 'doc-root' at its root, but the 'el' element itself. I would very much like to validate it against the existing schema then, but just running it through a validating parser wouldn't work, since it will expect a 'doc-root' at the root. So, again, the question is, - how can one validate a document fragment against an existing schema, or, perhaps, how can a schema be written to allow such an approach. Hope it made sense.

    Read the article

  • XML deserialization doubling up on entities

    - by Nathan Loding
    I have an XML file that I am attempting to deserialize into it's respective objects. It works great on most of these objects, except for one item that is being doubled up on. Here's the relevant portion of the XML: <Clients> <Client Name="My Company" SiteID="1" GUID="xxx-xxx-xxx-xxx"> <Reports> <Report Name="First Report" Path="/Custom/FirstReport"> <Generate>true</Generate> </Report> </Reports> </Client> </Clients> "Clients" is a List<Client> object. Each Client object has a List<Report> object within it. The issue is that when this XML is deserialized, the List<Report> object has a count of 2 -- the "First Report" Report object is in there twice. Why? Here's the C#: public class Client { [System.Xml.Serialization.XmlArray("Reports"), System.Xml.Serialization.XmlArrayItem(typeof(Report))] public List<Report> Reports; } public class Report { [System.Xml.Serialization.XmlAttribute("Name")] public string Name; public bool Generate; [System.Xml.Serialization.XmlAttribute("Path")] public string Path; } class Program { static void Main(string[] args) { List<Client> _clients = new List<Client>(); string xmlFile = "myxmlfile.xml"; System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Client>), new System.Xml.Serialization.XmlRootAttribute("Clients")); using (FileStream stream = new FileStream(xmlFile, FileMode.Open)) { _clients = xmlSerializer.Deserialize(stream) as List<Client>; } foreach(Client _client in _clients) { Console.WriteLine("Count: " + _client.Reports.Count); // This write "2" foreach(Report _report in _client.Reports) { Console.WriteLine("Name: " + _report.Name); // Writes "First Report" twice } } } }

    Read the article

  • Issue allowing custom Xml Serialization/Deserialization on certain types of field

    - by sw1sh
    I've been working with Xml Serialization/Deserialization in .net and wanted a method where the serialization/deserialization process would only be applied to certain parts of an Xml fragment. This is so I can keep certain parts of the fragment in Xml after the deserialization process. To do this I thought it would be best to create a new class (XmlLiteral) that implemented IXmlSerializable and then wrote specific code for handling the IXmlSerializable.ReadXml and IXmlSerializable.WriteXml methods. In my example below this works for Serializing, however during the Deserialization process it fails to run for multiple uses of my XmlLiteral class. In my example below sTest1 gets populated correctly, but sTest2 and sTest3 are empty. I'm guessing I must be going wrong with the following lines but can't figure out why.. Any ideas at all? Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Full listing: Imports System Imports System.Xml.Serialization Imports System.Xml Imports System.IO Imports System.Text Public Class XmlLiteralExample Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim MyObjectInstance As New MyObject MyObjectInstance.aProperty = "MyValue" MyObjectInstance.XmlLiteral1 = New XmlLiteral("<test1>Some Value</test1>") MyObjectInstance.XmlLiteral2 = New XmlLiteral("<test2>Some Value</test2>") MyObjectInstance.XmlLiteral3 = New XmlLiteral("<test3>Some Value</test3>") ' quickly serialize the object to Xml Dim sw As New StringWriter(New StringBuilder()) Dim s As New XmlSerializer(MyObjectInstance.[GetType]()), xmlnsEmpty As New XmlSerializerNamespaces xmlnsEmpty.Add("", "") s.Serialize(sw, MyObjectInstance, xmlnsEmpty) Dim XElement As XElement = XElement.Parse(sw.ToString()) ' XElement reads as the following, so serialization works OK '<MyObject> ' <aProperty>MyValue</aProperty> ' <XmlLiteral1> ' <test1>Some Value</test1> ' </XmlLiteral1> ' <XmlLiteral2> ' <test2>Some Value</test2> ' </XmlLiteral2> ' <XmlLiteral3> ' <test3>Some Value</test3> ' </XmlLiteral3> '</MyObject> ' quickly deserialize the object back to an instance of MyObjectInstance2 Dim MyObjectInstance2 As New MyObject Dim xmlReader As XmlReader, x As XmlSerializer xmlReader = XElement.CreateReader x = New XmlSerializer(MyObjectInstance2.GetType()) MyObjectInstance2 = x.Deserialize(xmlReader) Dim sProperty As String = MyObjectInstance2.aProperty ' equal to "MyValue" Dim sTest1 As String = MyObjectInstance2.XmlLiteral1.Text ' contains <test1>Some Value</test1> Dim sTest2 As String = MyObjectInstance2.XmlLiteral2.Text ' is empty Dim sTest3 As String = MyObjectInstance2.XmlLiteral3.Text ' is empty ' sTest3 and sTest3 should be populated but are not? xmlReader = Nothing End Sub Public Class MyObject Private _aProperty As String Private _XmlLiteral1 As XmlLiteral Private _XmlLiteral2 As XmlLiteral Private _XmlLiteral3 As XmlLiteral Public Property aProperty As String Get Return _aProperty End Get Set(ByVal value As String) _aProperty = value End Set End Property Public Property XmlLiteral1 As XmlLiteral Get Return _XmlLiteral1 End Get Set(ByVal value As XmlLiteral) _XmlLiteral1 = value End Set End Property Public Property XmlLiteral2 As XmlLiteral Get Return _XmlLiteral2 End Get Set(ByVal value As XmlLiteral) _XmlLiteral2 = value End Set End Property Public Property XmlLiteral3 As XmlLiteral Get Return _XmlLiteral3 End Get Set(ByVal value As XmlLiteral) _XmlLiteral3 = value End Set End Property Public Sub New() _XmlLiteral1 = New XmlLiteral _XmlLiteral2 = New XmlLiteral _XmlLiteral3 = New XmlLiteral End Sub End Class <System.Xml.Serialization.XmlRootAttribute(Namespace:="", IsNullable:=False)> _ Public Class XmlLiteral Implements IXmlSerializable Private _src As String Public Property Text() As String Get Return _src End Get Set(ByVal value As String) _src = value End Set End Property Public Sub New() _src = "" End Sub Public Sub New(ByVal Text As String) _src = Text End Sub #Region "IXmlSerializable Members" Private Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema Return Nothing End Function Private Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements IXmlSerializable.ReadXml Dim StringType As String = "" If reader.IsEmptyElement OrElse reader.Read() = False Then Exit Sub End If _src = reader.ReadOuterXml() End Sub Private Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements IXmlSerializable.WriteXml writer.WriteRaw(_src) End Sub #End Region End Class End Class

    Read the article

  • Problem with XML Deserialization C#

    - by alex
    I am having trouble with XML deserialization. In a nutshell - I have 2 classes: SMSMessage SMSSendingResponse I call an API that takes a bunch of parameters (represented by SMSMessage class) It returns an XML response. The response looks like this: <?xml version="1.0" encoding="utf-8"?> <data> <status>1</status> <message>OK</message> <results> <result> <account>12345</account> <to>012345678</to> <from>054321</from> <message>Testing</message> <flash></flash> <replace></replace> <report></report> <concat></concat> <id>f8d3eea1cbf6771a4bb02af3fb15253e</id> </result> </results> </data> Here is the SMSMessage class (with the xml serialization attributes so far) using System.Xml.Serialization; namespace XMLSerializationHelp { [XmlRoot("results")] public class SMSMessage { public string To { get { return Result.To; } } public string From { get { return Result.From; } } public string Message { get { return Result.Message; } } [XmlElement("result")] public Result Result { get; set; } } } Here is SMSMessageSendingResponse: using System.Xml.Serialization; namespace XMLSerializationHelp { [XmlRoot("data")] public class SMSSendingResponse { //should come from the results/result/account element. in our example "12345" public string AccountNumber { get { return SMSMessage.Result.AccountNumber; } } //should come from the "status" xml element [XmlElement("status")] public string Status { get; set; } //should come from the "message" xml element (in our example - "OK") [XmlElement("message")] public string Message { get; set; } //should come from the "id" xml element (in our example - "f8d3eea1cbf6771a4bb02af3fb15253e") public string ResponseID { get { return SMSMessage.Result.ResponseID; } } //should be created from the results/result element - ignore flash, replace, report and concat elements for now. [XmlElement("results")] public SMSMessage SMSMessage { get; set; } } } Here is the other class (Result) - I want to get rid of this, so only the 2 previously mentioned classes remain using System.Xml.Serialization; namespace XMLSerializationHelp { [XmlRoot("result")] public class Result { [XmlElement("account")] public string AccountNumber{ get; set; } [XmlElement("to")] public string To { get; set; } [XmlElement("from")] public string From { get; set; } [XmlElement("message")] public string Message { get; set; } [XmlElement("id")] public string ResponseID { get; set; } } } I don't want SMSMessage to be aware of the SMSSendingResponse - as this will be handled by a different part of my application

    Read the article

  • How to retain XML string as a string field during XML deserialization

    - by detale
    I got an XML input string and want to deserialize it to an object which partially retain the raw XML. <SetProfile> <sessionId>A81D83BC-09A0-4E32-B440-0000033D7AAD</sessionId> <profileDataXml> <ArrayOfProfileItem> <ProfileItem> <Name>Pulse</Name> <Value>80</Value> </ProfileItem> <ProfileItem> <Name>BloodPresure</Name> <Value>120</Value> </ProfileItem> </ArrayOfProfileItem> </profileDataXml> </SetProfile> The class definition: public class SetProfile { public Guid sessionId; public string profileDataXml; } I hope the deserialization syntax looks like string inputXML = "..."; // the above XML XmlSerializer xs = new XmlSerializer(typeof(SetProfile)); using (TextReader reader = new StringReader(inputXML)) { SetProfile obj = (SetProfile)xs.Deserialize(reader); // use obj .... } but XMLSerializer will throw an exception and won't output < profileDataXml 's descendants to "profileDataXml" field in raw XML string. Is there any way to implement the deserialization like that?

    Read the article

  • gwt+xml- can i read through incomplete XML using the GWT XML Parser

    - by Arvind
    I have a requirement where a user is typing in XML in a text area, and I want to show the various nodes in a tree...But as the user is typing in the xml, it wont be a complete xml (since he is still typing in the XML)... How do I read an incomplete XML and correctly generate the tree? I understand how to read an xml and generate nodes in the tree, what I want to know is, how to read the incomplete XML as it is being typed in

    Read the article

  • Why isn't the Spring AOP XML schema properly loaded when Tomcat loads & reads beans.xml

    - by chrisbunney
    I'm trying to use Spring's Schema Based AOP Support in Eclipse and am getting errors when trying to load the configuration in Tomcat. There are no errors in Eclipse and auto-complete works correctly for the aop namespace, however when I try to load the project into eclipse I get this error: 09:17:59,515 WARN XmlBeanDefinitionReader:47 - Ignored XML validation warning org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/aop/spring-aop-2.5.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not . Followed by: SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 39 in XML document from /WEB-INF/beans.xml is invalid; nested exception is org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aop:config'. Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'aop:config'. Based on this, it seems the schema is not being read when Tomcat parses the beans.xml file, leading to the <aop:config> element not being recognised. My beans.xml file is as follows: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!--import resource="classpath:META-INF/cxf/cxf.xml" /--> <!--import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /--> <!--import resource="classpath:META-INF/cxf/cxf-servlet.xml" /--> <!-- NOTE: endpointName attribute maps to wsdl:port@name & should be the same as the portName attribute in the @WebService annotation on the IWebServiceImpl class --> <!-- NOTE: serviceName attribute maps to wsdl:service@name & should be the same as the serviceName attribute in the @WebService annotation on the ASDIWebServiceImpl class --> <!-- NOTE: address attribute is the actual URL of the web service (relative to web app location) --> <jaxws:endpoint xmlns:tns="http://iwebservices.ourdomain/" id="iwebservices" implementor="ourdomain.iwebservices.IWebServiceImpl" endpointName="tns:IWebServiceImplPort" serviceName="tns:IWebService" address="/I" wsdlLocation="wsdl/I.wsdl"> <!-- To have CXF auto-generate WSDL on the fly, comment out the above wsdl attribute --> <jaxws:features> <bean class="org.apache.cxf.feature.LoggingFeature" /> </jaxws:features> </jaxws:endpoint> <aop:config> <aop:aspect id="myAspect" ref="aBean"> </aop:aspect> </aop:config> </beans> The <aop:config> element in my beans.xml file is copy-pasted from the Spring website to try and remove any possible source of error Can anyone shed any light on why this error is occurring and what I can do to fix it?

    Read the article

  • Create an XML file using Datasets Using info from XML Schema

    - by Voulnet
    Hello there, I have been thinking about the optimal way to create an XML file using data from a Dataset AND according to the rules of an XML schema. I've been searching around for a bit, and I failed to find a way in which I only take the data from the Dataset and put it inside a XML tags, with the tags being defined by an already-existing schema. So it might go like this: 1- Create Dataset and fill its rows with data. 2- Create an XML according to an XML schema rules. 3- Fill said XML file with data from Dataset such that data is taken from the Dataset while structure of the XML file is taken from the XML schema.

    Read the article

  • Namespaces and deserialization issue

    - by CaffGeek
    UPDATE: You can run the code at the end of this to recreate and see the error I am having and hopefully solve it! UPDATE2: It's not the removal of the xmlns="" that's the issue... as you can remove it from the initial xml string. The problem is with the [XmlType(TypeName = "Systems")] somehow causing it to be added... UPDATE3: Turns out the problem is in here, I need to set the TypeName based on what is in the existing, XmlTypeAttribute if it already exists on the class.... xmlAttributes.XmlType = new XmlTypeAttribute { Namespace = "" }; I get the following XML as a string from a webservice <Systems xmlns=""> <System id="1"> <sys_name>ALL</sys_name> </System> <System id="2"> <sys_name>asdfasdf</sys_name> </System> <System id="3"> <sys_name>fasdfasf</sys_name> </System> <System id="4"> <sys_name>asdfasdfasdf</sys_name> </System> </Systems> I then execute this, to convert it to an object result = XElement.Parse(xmlResult.OuterXml).Deserialize<AwayRequestSystems>(); Strangely though, in the Deserialize method, while the RemoveAllNamespaces works and returns the xml without the namespace I get the error <Systems xmlns=''> was not expected. in the catch when return (T) serializer.Deserialize(reader); executes! Why is it doing this? The xmlns is GONE!!! EXECUTABLE CODE! (Just put it in a test project) using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Xml.Serialization; namespace DeserializationTest { [TestClass] public class UnitTest1 { public TestContext TestContext { get; set; } [TestMethod] public void RemoveXmlnsFromSystems() { var xml = XElement.Parse(@"<Systems xmlns=""""> <System id=""1""> <sys_name>ALL</sys_name> </System> <System id=""2""> <sys_name>ePO</sys_name> </System> <System id=""3""> <sys_name>iEFT</sys_name> </System> <System id=""4""> <sys_name>Away Requests</sys_name> </System> <System id=""5""> <sys_name>RP3</sys_name> </System> </Systems>"); var systems = xml.Deserialize<AwayRequestSystems>(); Assert.IsInstanceOfType(systems, typeof(AwayRequestSystems)); var xmlnsFree = xml.RemoveAllNamespaces(); var str = xmlnsFree.ToString(); Debug.WriteLine(str); Assert.AreNotEqual("Error", xmlnsFree.Name.ToString(), "Serialization Error"); Assert.IsFalse(str.Contains("xmlns"), "Xmlns still exists"); } } [XmlType(TypeName = "Systems")] public class AwayRequestSystems : List<AwayRequestSystem> { } [XmlType(TypeName = "System")] public class AwayRequestSystem { [XmlAttribute("id")] public int ID { get; set; } [XmlElement("sys_name")] public string Name { get; set; } } public static class XmlSerializerFactory { private static Dictionary<Type, XmlSerializer> _serializers = new Dictionary<Type, XmlSerializer>(); public static void ResetCache() { _serializers = new Dictionary<Type, XmlSerializer>(); } public static XmlSerializer GetSerializerFor(Type typeOfT) { if (!_serializers.ContainsKey(typeOfT)) { var xmlAttributes = new XmlAttributes(); var xmlAttributeOverrides = new XmlAttributeOverrides(); Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT)); xmlAttributes.XmlType = new XmlTypeAttribute { Namespace = "" }; xmlAttributes.Xmlns = false; var types = new List<Type> { typeOfT, typeOfT.BaseType }; foreach (var property in typeOfT.GetProperties()) { types.Add(property.PropertyType); } types.RemoveAll(t => t.ToString().StartsWith("System.")); foreach (var type in types) { if (xmlAttributeOverrides[type] == null) xmlAttributeOverrides.Add(type, xmlAttributes); } var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides); //var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides, types.ToArray(), new XmlRootAttribute(), string.Empty); //var newSerializer = new XmlSerializer(typeOfT, string.Empty); _serializers.Add(typeOfT, newSerializer); } return _serializers[typeOfT]; } } public static class XElementExtensions { public static XElement RemoveAllNamespaces(this XElement source) { if (source.HasAttributes) source.Attributes().Where(a => a.Name.LocalName.Equals("xmlns")).Remove(); return source.HasElements ? new XElement(source.Name.LocalName, source.Attributes()/*.Where(a => !a.Name.LocalName.Equals("xmlns"))*/, source.Elements().Select(el => RemoveAllNamespaces(el)) ) : new XElement(source.Name.LocalName) { Value = source.Value }; } } public static class SerializationExtensions { public static XElement Serialize(this object source) { try { var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType()); var xdoc = new XDocument(); using (var writer = xdoc.CreateWriter()) { serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") })); } var result = (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing"); return result.RemoveAllNamespaces(); } catch (Exception x) { return new XElement("Error", x.ToString()); } } public static T Deserialize<T>(this XElement source) where T : class { //try //{ var serializer = XmlSerializerFactory.GetSerializerFor(typeof(T)); var cleanxml = source.RemoveAllNamespaces(); var reader = cleanxml.CreateReader(); return (T)serializer.Deserialize(reader); //} //catch (Exception x) //{ // return null; //} } } }

    Read the article

  • XML Serialization in C# without XML attribute nodes

    - by Alex Marshall
    Hello, I have an XML document format from a legacy system that I have to support in a future application. I want to be able to both serialize and deserialize the XML between XML and C# objects, however, using the objects generated by xsd.exe, the C# serialization includes the xmlns:xsi..., xsi:... etc XML attributes on the root element of the document that gets generated. Is there anyway to disable this so that absolutely no XML attribute nodes get put out in the resulting XML ? The XML document should be elements only. Duplicate? XmlSerializer: remove unnecessary xsi and xsd namespaces

    Read the article

  • <?xml version=“1.0” encoding=“UTF-8”?> not <?xml version='1.0' encoding='UTF-8'?>

    - by user2446702
    I am using lxml with tree.write(xmlFileOut, pretty_print = True, xml_declaration = True, encoding='UTF-8' to write out my opened and edited xml file, but I absolutely need to have the xml declaration as <?xml version=“1.0” encoding=“UTF-8”?> and NOT <?xml version='1.0' encoding='UTF-8'?> Now I know they are exactly the same when it comes to xml, but I am dealing with a very tricky customer who absolutely has to have " in the declaration and not '. I have searched everywhere but can't find the answer. Could I create it and add it in myself to the head of the xml somehow? Could I tell lxml that this is what I need as an xml declaration?

    Read the article

  • Deserialize an XML file - an error in xml document (1,2)

    - by Lindsay Fisher
    I'm trying to deserialize an XML file which I receive from a vendor with XmlSerializer, however im getting this exception: There is an error in XML document (1, 2).InnerException Message "<delayedquotes xmlns=''> was not expected.. I've searched the stackoverflow forum, google and implemented the advice, however I'm still getting the same error. Please find the enclosed some content of the xml file: <delayedquotes id="TestData"> <headings> <title/> <bid>bid</bid> <offer>offer</offer> <trade>trade</trade> <close>close</close> <b_time>b_time</b_time> <o_time>o_time</o_time> <time>time</time> <hi.lo>hi.lo</hi.lo> <perc>perc</perc> <spot>spot</spot> </headings> <instrument id="Test1"> <title id="Test1">Test1</title> <bid>0</bid> <offer>0</offer> <trade>0</trade> <close>0</close> <b_time>11:59:00</b_time> <o_time>11:59:00</o_time> <time>11:59:00</time> <perc>0%</perc> <spot>0</spot> </instrument> </delayedquotes> and the code [Serializable, XmlRoot("delayedquotes"), XmlType("delayedquotes")] public class delayedquotes { [XmlElement("instrument")] public string instrument { get; set; } [XmlElement("title")] public string title { get; set; } [XmlElement("bid")] public double bid { get; set; } [XmlElement("spot")] public double spot { get; set; } [XmlElement("close")] public double close { get; set; } [XmlElement("b_time")] public DateTime b_time { get; set; } [XmlElement("o_time")] public DateTime o_time { get; set; } [XmlElement("time")] public DateTime time { get; set; } [XmlElement("hi")] public string hi { get; set; } [XmlElement("lo")] public string lo { get; set; } [XmlElement("offer")] public double offer { get; set; } [XmlElement("trade")] public double trade { get; set; } public delayedquotes() { } }

    Read the article

  • XML deserialization doesn't read in second level

    - by Andy
    Sorry if the title doesn't make much sense, but I'm not too familiar with the terminology. My question is: I have a config.xml file for a program I'm working on. I created an xsd file by 'xsd.exe config.xml'. I then took this xsd and added it to the solution in visual studio. My last step used a program called xsd2code that turned that xsd file into a class I can serialize too. The problem is it doesn't read more then a layer deep in the xml tree. By this I mean the elements in the root node get deserialized into my object, but those that are in a node inside the root node are not. I found this out by putting a breakpoint after the deserialization and looking at my object. Any Ideas? Let me know if this needs some clarification or you need a snippet of something.

    Read the article

  • Using VTD-XML to modify element text only

    - by Algorist
    Hi, I want to achieve below thing in vtd-xml xml modifier class. Original xml <xml> <element attr1='1' attr2='2' attr3='3'>text</element> </xml> int p = vn.getText() xm.updateToken(p, "new text"); But the code here is not modifying the text to new text. Any idea how to achieve this? Other option is to call xm.remove() and then add tag. But, I am not able to retain the attributes. Thank you Bala

    Read the article

  • Wrapping Arbitrary XML within XML

    - by Marc C
    I need to embed arbitrary (syntactically valid) XML documents within a wrapper XML document. The embedded documents are to be regarded as mere text, they do not need to be parseable when parsing the wrapper document. I know about the "CDATA trick", but I can't use that if the inner XML document itself contains a CDATA segment, and I need to be able to embed any valid XML document. Any advice on accomplishing this--or working around the CDATA limitation--would be appreciated.

    Read the article

  • XML Parsing from Non-XML Document

    - by Neel Basu
    in a xml/non-xml File there may exist some XML Block that I need to parse and replace with some other string.. The Scenario is something like this.. Some Text <cnt:use name="abc" call="xyz"> <cnt:param name="x" value="2" /> </cnt:use> Some Text There is no guarantee that the document is a proper XML document. (there may exist some unclosed Tags. or some other common mistakes that a Stupid people can make while typing HTML). so I can't use SAX or DOM. I can't even pass it to XSLT (am I right ?). So Whats the best way to extract the <cnt:*> part from the non-xml Document. and read it then replace with something else.

    Read the article

  • How to transport an XML fragment in an XML Document

    - by mrwayne
    Hi, I'm using an AJAX system on a web application, and for one of the objects i return, it needs to contain an xml fragment. Unfortunately, being AJAX, i'm sending the values back via XML already. So, at the moment, i have something that looks like this (ignoring the fact the tags arent perfect. <Transport> <Message> <Content><[CDATA...] XML Content in here </Cdata></Content> </Message> </Transport> This has worked pretty well for the last few years, however, now the XML content itself needs to contain its own CDATA tags and its causing me grief because you cannot nest CDATA sections. Is there another way to encode the 'XML Content' internally?

    Read the article

  • Programatically determining which node in an XML document caused validation against its XML Schema t

    - by jd1212
    My input is a well-formed XML document and a corresponding XML Schema document. What I would like to do is determine the location within the XML document that causes it to fail validation against the XML Schema document. I could not figure out how to do this using the standard validation approach in Java: SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema(... /* the .xsd source */); Validator validator = schema.newValidator(); DocumentBuilderFactory ... DocumentBuilder ... Document document = DocumentBuilder.parse(... /* the .xml source */); try { validator.validate(new DOMSource(document)); ... } catch (SAXParseException e) { ... } I have toyed with the idea of getting at least the line and column number from SAXParseException, but they're always set to -1, -1 on validation error.

    Read the article

  • Free lightweight XML text editor to include with an application

    - by Heinzi
    Our application uses a XML configuation file. I thought that it would be nice to distribute some small, lightweight XML editor with our application that the user can use to edit the config file. Features should be: Small and lightweight (ideally, a small .exe that does not require installation), free, with license terms that permit distributing it with a commercial application, understands XML schemas (auto-completion, show validation errors). Does anyone know of such an editor?

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >