Search Results

Search found 259 results on 11 pages for 'xmlserializer'.

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

  • Using generics with XmlSerializer

    - by MainMa
    Hi, When using XML serialization in C#, I use code like this: public MyObject LoadData() { XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyObject)); using (TextReader reader = new StreamReader(settingsFileName)) { return (MyObject)xmlSerializer.Deserialize(reader); } } (and similar code for deserialization). It requires casting and is not really nice. Is there a way, directly in .NET Framework, to use generics with serialization? That is to say to write something like: public MyObject LoadData() { // Generics here. XmlSerializer<MyObject> xmlSerializer = new XmlSerializer(); using (TextReader reader = new StreamReader(settingsFileName)) { // No casts nevermore. return xmlSerializer.Deserialize(reader); } }

    Read the article

  • How can I validate the output of XmlSerializer?

    - by Tim Jansen
    In C# / .NET 2.0, when I serialize an object using XmlSerializer, what's the easiest way to validate the output against an XML schema? The problem is that it is all too easy to write invalid XML with the XmlSerializer, and I can't find a way to validate the XML that does not look cumbersome. Ideally I would expect to set the schema in the XmlSerializer or to have a XmlWriter that validates.

    Read the article

  • How do I add a default namespace with no prefix using XMLSerializer

    - by OldBob
    Hi Using C# and .Net 3.5; I am trying to generate an XML document that contains the default namespace without a prefix using XMLSerializer. eg. <?xml version="1.0" encoding="utf-8" ?> <MyRecord ID="9266" xmlns="http://www.website.com/MyRecord"> <List> <SpecificItem> using the following code string xmlizedString = null; MemoryStream memoryStream = new MemoryStream(); XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord)); XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces(); xmlnsEmpty.Add(string.Empty, string.Empty); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray()); and class structure [Serializable] [XmlRoot("MyRecord")] public class ExportMyRecord { [XmlAttribute("ID")] public int ID { get; set; } Now, I've tried various options XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord),"http://www.website.com/MyRecord"); or [XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")] gives me <?xml version="1.0" encoding="utf-8"?> <q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord"> <q1:List> <q1:SpecificItem> I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives. Any suggestions? No responses so far. Has anyone experienced this or know how to solve it?

    Read the article

  • Why is XmlSerializer so hard to use?

    - by mafutrct
    I imagine to use XML serialization like this: class Foo { public Foo (string name) { Name1 = name; Name2 = name; } [XmlInclude] public string Name1 { get; private set; } [XmlInclude] private string Name2; } StreamWriter wr = new StreamWriter("path.xml"); new XmlSerializer<Foo>().Serialize (wr, new Foo ("me")); But this does not work at all: XmlSerializer is not generic. I have to cast from and to object on (de)serialization. Every property has to be fully public. Why aren't we just using Reflection to access private setters? Private fields cannot be serialized. I'd like to decorate private fields with an attribute to have XmlSerializer include them. Did I miss something and XmlSerializer is actually offering the described possibilities? Are there alternate serializers to XML that handle these cases more sophisticatedly? If not: We're in 2010 after all, and .NET has been around for many years. XML serialization is often used, totally standard and should be really easy to perform. Or is my understanding possibly wrong and XML serialization ought not to expose the described features for a good reason? (Feel free to adjust caption or tags. If this should be CW, please just drop a note.)

    Read the article

  • Why doesn't XmlSerializer support Dictionary?

    - by theburningmonk
    Just curious as to why Dictionary is not supported by XmlSerializer? You can get around it easily enough by using DataContractSerializer and writing the object to a XmlTextWriter, but what are the characteristics of a Dictionary that makes it difficult for a XmlSerializer to deal with considering it's really an array of KeyValuePairs. In fact, you can pass an IDictionary<TKey, TItem> to a method expecting an IEnumerable<KeyValuePairs<TKey, ITem>>.

    Read the article

  • XmlSerializer Deserialize failures

    - by smvlad
    I have wsdl from third party server. Method that i'm interested in returns XmlNode. My thought was wrap web methods and use XmlSerializer to return strongly typed objects. Returned xml looks like this (i removed soap headers): <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ResponseExt" xmlns="http://www.thirdparty.com/lr/"> <Code>0</Code> <Message>SUCCESS</Message> <SessionId>session_token</SessionId> </Response> Looked simple. Created a class: [XmlRoot("Response")] public class MyClass { public string Code {get; set;} public string Message {get; set;} public string SessionId {get; set;} } Processing time: //XmlNode node = xml from above XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); XmlNodeReader reader = new XmlNodeReader(node); Myclass myclass = serializer.Deserialize(reader) as MyClass Last line is where it blows up with inner exception message: The specified type was not recognized: name='ResponseExt', namespace='http://www.thirdparty.com/lr/', at . I can't figure out how to make Serializer happy and what exactly these two mean xsi:type="ResponseExt" xmlns="http://www.thirdparty.com/lr/ As always any advice and pointer are appreciated

    Read the article

  • Interchange xsd and xsi - XmlSerializer in c#

    - by Sri Kumar
    Hello All, XmlSerializer serializer = new XmlSerializer(typeof(IxComment)); System.IO.StringWriter aStream = new System.IO.StringWriter(); serializer.Serialize(aStream,Comments); commentsString = aStream.ToString(); Here the commentsString has the the following element in it <IxComment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Is there any possibility to interchange the xsi and xsd attribute and get the element as shown below <IxComment xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > Will this cause any other issue?

    Read the article

  • .NET OutOfMemoryException on XMLSerializer.Serialize

    - by Micah
    I have a web site that is throwing OutOfMemoryExceptions on whenever it gets to the following spot in my code: XmlSerializer xs = new XmlSerializer(t, xoverrides); Seeing how this only happens when it is on the web server, i don't have a ton of information on why this is happening. I know that the objects that it is serializing aren't anything too serious-- definitely less than a MB each. Have you had this before? Feel like helping me diagnose the issue? Any help is appreciated. Thanks!

    Read the article

  • XmlSerializer one Class that has multiple classes properties

    - by pee2002
    Hi there! Objective: Serialize all the public properties of the ClassMain: public class ClassMain { ClassA classA = new ClassA(); public ClassMain() { classA.Prop1 = "Prop1"; classA.Prop2 = "Prop2"; } public string Prop1 { get; set; } public string Prop2 { get; set; } public ClassA ClassA { get { return classA; } } } ClassA: public class ClassA { public string Prop1 { get; set; } public string Prop2 { get; set; } } This is how i´m serializing: private void button1_Click(object sender, EventArgs e) { ClassMain classMain = new ClassMain(); classMain.Prop1 = "Prop1"; classMain.Prop2 = "Prop2"; XmlSerializer mySerializer = new XmlSerializer(typeof(ClassMain)); StreamWriter myWriter = new StreamWriter("xml1.xml"); mySerializer.Serialize(myWriter, classMain); myWriter.Close(); } In this case, the xml output is: <?xml version="1.0" encoding="utf-8"?> <ClassMain xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Prop1>Prop1</Prop1> <Prop2>Prop2</Prop2> </ClassMain> As you see, is lacking the ClassA properties. Can anyone help me out? Regards

    Read the article

  • Using XmlSerializer deserialize complex type elements are null

    - by Jean Bastos
    I have the following schema: <?xml version="1.0"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tipos="http://www.ginfes.com.br/tipos_v03.xsd" targetNamespace="http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_resposta_v03.xsd" xmlns="http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_resposta_v03.xsd" attributeFormDefault="unqualified" elementFormDefault="qualified"> <xsd:import schemaLocation="tipos_v03.xsd" namespace="http://www.ginfes.com.br/tipos_v03.xsd" /> <xsd:element name="ConsultarSituacaoLoteRpsResposta"> <xsd:complexType> <xsd:choice> <xsd:sequence> <xsd:element name="NumeroLote" type="tipos:tsNumeroLote" minOccurs="1" maxOccurs="1"/> <xsd:element name="Situacao" type="tipos:tsSituacaoLoteRps" minOccurs="1" maxOccurs="1"/> </xsd:sequence> <xsd:element ref="tipos:ListaMensagemRetorno" minOccurs="1" maxOccurs="1"/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> and the following class: [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.ginfes.com.br/servico_consultar_situacao_lote_rps_envio_v03.xsd", IsNullable = false)] public partial class ConsultarSituacaoLoteRpsEnvio { [System.Xml.Serialization.XmlElementAttribute(Order = 0)] public tcIdentificacaoPrestador Prestador { get; set; } [System.Xml.Serialization.XmlElementAttribute(Order = 1)] public string Protocolo { get; set; } } Use the following code to deserialize the object: XmlSerializer respSerializer = new XmlSerializer(typeof(ConsultarSituacaoLoteRpsResposta)); StringReader reader = new StringReader(resp); ConsultarSituacaoLoteRpsResposta respModel = (ConsultarSituacaoLoteRpsResposta)respSerializer.Deserialize(reader); does not occur any error but the properties of objects are null, anyone know what is happening?

    Read the article

  • Android XmlSerializer limitation?

    - by Rexb
    Hi all, My task is just to get an xml string using XmlSerializer. Problem is that it seems like the serializer stops adding any new element and/or attribute to the xml document when it reaches certain length (perhaps 10,000 char?). My questions: have you experience this kind of problem? What could be possible solutions? Here is my sample test code: public void doSerialize() throws XmlPullParserException, IllegalArgumentException, IllegalStateException, IOException { StringWriter writer = new StringWriter(); XmlSerializer serializer = XmlPullParserFactory.newInstance().newSerializer(); serializer.setOutput(writer); serializer.startDocument(null, null); serializer.startTag(null, "START"); for (int i = 0; i < 20; i++) { serializer.attribute(null, "ATTR" + i, "VAL " + i); } serializer.startTag(null, "DATA"); for (int i = 0; i < 500; i++) { serializer.attribute(null, "attr" + i, "value " + i); } serializer.endTag(null, "DATA"); serializer.endTag(null, "START"); serializer.endDocument(); String xml = writer.toString(); // value: until 493rd attribute int n = xml.length(); // value: 10125 } Any help will be greatly appreciated.

    Read the article

  • Interchange xsd and xsi in the output of XmlSerializer

    - by Sri Kumar
    XmlSerializer serializer = new XmlSerializer(typeof(IxComment)); System.IO.StringWriter aStream = new System.IO.StringWriter(); serializer.Serialize(aStream,Comments); commentsString = aStream.ToString(); Here the commentsString has the the following element in it <IxComment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> Is there any possibility to interchange the xsi and xsd attribute and get the element as shown below <IxComment xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > Will this cause any other issue? EDIT: Why do i need to do this? We are migrating an existing application from 1.1 to 3.0 and in the code there is a if loop int iStartTagIndex = strXMLString.IndexOf("<IxComment xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"); that check for the index of the IxComment. Here the o/p of the serializer and the condition differ in the position of xsd and xsi. So i am trying to know whether we can instruct the serializer to provided the o/p as required. I have another question here as this was an existing application does the serializer O/P differs with versions?

    Read the article

  • How to specify the order of XmlAttributes, using XmlSerializer

    - by demoncodemonkey
    XmlElement has an "Order" attribute which you can use to specify the precise order of your properties (in relation to each other anyway) when serializing using XmlSerializer. Is there a similar thing for XmlAttribute? I just want to set the order of the attributes from something like <MyType end="bob" start="joe" /> to <MyType start="joe" end="bob" /> This is just for readability, my own benefit really.

    Read the article

  • Automatically minifying attribute/element names when using XmlSerializer

    - by frou
    When serializing a C# class using XmlSerializer, the attributes/elements representing the properties of the class will have the same names as they do in the source code. I know you can override this by doing like so: [XmlAttribute("num")] public int NumberOfThingsThatAbcXyz { get; set; } I'd like the generated XML for my classes to be as compact as possible, but obviously still capable of being automatically deserialized on the other side. Is there a way to have these names minified as much as possible without having to manually think of and annotate everything with a short string? The resultant XML being easily human readable isn't a concern.

    Read the article

  • XmlSerializer.Deserialize method appends timezone to a time and datetime field

    - by G33kKahuna
    Have a small script in Microsoft.NET 2.0 that deserializes a XML back to a typed object, connects dyanimcally to a web service using ServiceDescription and binds the deserialized typed object to the WebMethod inbound. The XML prior to serialization looks like below <completion_time>12:19:38</completion_time> on the wire when communicating to the web service looks like below <completion_time>12:19:38.0000000-04:00</completion_time> with the timezone appended to the end. This is causing the time to be read differently when communicating to a web service at a different timezone. is there anyway to let XmlSerializer skip the timezone? Or any other known workarounds?

    Read the article

  • XmlSerializer equivalent of IExtensibleDataObject

    - by demoncodemonkey
    With DataContracts you can derive from IExtensibleDataObject to allow round-tripping to work without losing any unknown additional data from your XML file. I can't use DataContract because I need to control the formatting of the output XML. But I also need to be able to read a future version of the XML file in the old version of the app, without losing any of the data from the XML file. e.g. XML v1: <Person> <Name>Fred</Name> </Person> XML v2: <Person> <Name>Fred</Name> <Age>42</Age> </Person> If reading an XML v2 file from v1 of my app, deserializing and serializing it again turns it into an XML v1 file. i.e. the "Age" field is erased. Is there anything similar to IExtensibleDataObject that I can use with XmlSerializer to avoid the Age field disappearing?

    Read the article

  • How to send a XmlSerializer Class to a WebService and then Deserialize it?

    - by pee2002
    Hi! I want to be able to send a XmlSerializer class (which is generated obvious in remote C# application) over a WebService that will then deserialize it into a class. (I didnt know it its possible either) My class is: SystemInfo I'm serializing it this way: XmlSerializer mySerializer = new XmlSerializer(typeof(SystemInfo)); StreamWriter myWriter = new StreamWriter(textBox1.Text); mySerializer.Serialize(myWriter, sysinfo); How can i build the WebService? [WebMethod] public void Reports(XmlSerializer xmlSerializer) { . . . } Can anyone help me out? Regards

    Read the article

  • Handling FormatExceptions using XmlSerializer.Deserialize

    - by qntmfred
    I have a third party web service that returns this xml <book> <release_date>0000-00-00</release_date> </book> I am trying to deserialize it into this class public class Book { [XmlElement("release_date")] public DateTime ReleaseDate { get; set; } } But because 0000-00-00 isn't a valid DateTime, I get a FormatException. What's the best way to handle this?

    Read the article

  • OutOfMemoryError calling XmlSerializer.Deserialize() - not related to XML size!

    - by Mike Atlas
    This is a really crazy bug. The following is throwing an OutOfMemoryException, for XML snippits that are very short (e.g., <ABC def='123'/>) of one type, but not for others of the same size but a different type: (e.g., <ZYX qpr='baz'/>). public static T DeserializeXmlNode<T>(XmlNode node) { try { return (T)new XmlSerializer(typeof(T)) .Deserialize(new XmlNodeReader(node)); } catch (Exception ex) { throw; // just for catching a breakpoint. } } I read in this MSDN article that if I were using XmlSerializer with additional parameters in the constructor, I'd end up generating un-cached serializer assemblies every it got called, causing an Assembly Leak. But I'm not using additional parameters in the constructor. It also happens on the first call, too, so the AppDomain is fresh. Worse yet, it is only thrown in release builds, not debug builds. What gives?

    Read the article

  • Java - HtmlUnit - Unable to save HTML to file (in some cases)

    - by Walter White
    Hi all, I am having intermittent issues saving the response HTML in HtmlUnit. Caused by: java.io.IOException: Unable to save file:C:\ccview\PP50773_4.0_walter\TSC_hca\Applications\HCA_J2EE\HCA\target\HtmlUnitTests\single\1\com\pnc\tsc\hca\ui\test\SiteCrawler\crawlSiteAsProvider\10.SiteCrawler.crawl.html at com.pnc.tsc.hca.ui.util.GetUtil.save(GetUtil.java:128) at com.pnc.tsc.hca.ui.util.GetUtil.add(GetUtil.java:75) at com.pnc.tsc.hca.ui.util.GetUtil.click(GetUtil.java:49) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:87) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:61) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:63) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:63) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:63) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawl(SiteCrawler.java:54) at com.pnc.tsc.hca.ui.test.SiteCrawler.crawlSiteAsProvider(SiteCrawler.java:50) ... 15 more Caused by: java.lang.RuntimeException: java.io.IOException: The system cannot find the path specified at com.gargoylesoftware.htmlunit.html.XmlSerializer.getAttributesFor(XmlSerializer.java:165) at com.gargoylesoftware.htmlunit.html.XmlSerializer.printOpeningTag(XmlSerializer.java:126) at com.gargoylesoftware.htmlunit.html.XmlSerializer.printXml(XmlSerializer.java:83) at com.gargoylesoftware.htmlunit.html.XmlSerializer.printXml(XmlSerializer.java:93) at com.gargoylesoftware.htmlunit.html.XmlSerializer.printXml(XmlSerializer.java:93) at com.gargoylesoftware.htmlunit.html.XmlSerializer.asXml(XmlSerializer.java:73) at com.gargoylesoftware.htmlunit.html.XmlSerializer.save(XmlSerializer.java:55) at com.gargoylesoftware.htmlunit.html.HtmlPage.save(HtmlPage.java:2259) at com.pnc.tsc.hca.ui.util.GetUtil.save(GetUtil.java:126) ... 24 more Caused by: java.io.IOException: The system cannot find the path specified at java.io.WinNTFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:883) at com.gargoylesoftware.htmlunit.html.XmlSerializer.createFile(XmlSerializer.java:216) at com.gargoylesoftware.htmlunit.html.XmlSerializer.getAttributesFor(XmlSerializer.java:160) ... 32 more Now, the parent directory exists and some other files have already been written to the directory. Looking at the filename, I don't see anything that would stand out as a red flag indicating the filename is bad. What can I do to correct this error? Thanks, Walter

    Read the article

  • Why is XmlSerializer throwing an InvalidOperationException?

    - by qster
    public void Save() { XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); /* A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll */ // .... } This is the whole class if you need it: public class DatabaseInformation { /* Create new database */ public DatabaseInformation(string name) { mName = name; NeedsSaving = true; mFieldsInfo = new List<DatabaseField>(); } /* Read from file */ public static DatabaseInformation DeserializeFromFile(string xml_file_path) { XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); TextReader r = new StreamReader(xml_file_path); DatabaseInformation ret = (DatabaseInformation)Serializer.Deserialize(r); r.Close(); ret.NeedsSaving = false; return ret; } /* Save */ public void Save() { XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation)); if (!mNeedsSaving) return; TextWriter w = new StreamWriter(Path.Combine(Program.MainView.CommonDirectory.Get(), Name + ".xml"), false); Serializer.Serialize(w, this); w.Close(); NeedsSaving = false; } private string mName; public string Name { get { return mName; } } private bool mNeedsSaving; public bool NeedsSaving { get { return mNeedsSaving; } set { mNeedsSaving = value; Program.MainView.UpdateTitle(value); } } private bool mHasId; public bool HasId { get { return mHasId; } } List<DatabaseField> mFieldsInfo; }

    Read the article

  • How to find an XPath query to Element/Element without namespaces (XmlSerializer, fragment)?

    - by Veksi
    Assume this simple XML fragment in which there may or may not be the xml declaration and has exactly one NodeElement as a root node, followed by exactly one other NodeElement, which may contain an assortment of various number of different kinds of elements. <?xml version="1.0"> <NodeElement xmlns="xyz"> <NodeElement xmlns=""> <SomeElement></SomeElement> </NodeElement> </NodeElement> How could I go about selecting the inner NodeElement and its contents without the namespace? For instance, "//*[local-name()='NodeElement/NodeElement[1]']" (and other variations I've tried) doesn't seem to yield results. As for in general the thing that I'm really trying to accomplish is to Deserialize a fragment of a larger XML document contained in a XmlDocument. Something like the following var doc = new XmlDocument(); doc.LoadXml(File.ReadAllText(@"trickynodefile.xml")); //ReadAllText to avoid Unicode trouble. var n = doc.SelectSingleNode("//*[local-name()='NodeElement/NodeElement[1]']"); using(var reader = XmlReader.Create(new StringReader(n.OuterXml))) { var obj = new XmlSerializer(typeof(NodeElementNodeElement)).Deserialize(reader); I believe I'm missing just the right XPath expression, which seem to be rather elusive. Any help much appreciated!

    Read the article

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