I would like to import an xml file and deserialize it into my model objects.
I am using C# MVC4 Asp.Net 4.51
I have tried a number of methods - if someone can provide some guidance on the best way to achieve this it would be appreciated.
I have tried but cannot get this to work:
public static KronosPunchRoundRuleSummary Deserialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(KronosPunchRoundRuleSummary));
TextReader textReader;
textReader = new StreamReader(#"c:\WSAPunchRoundRule.xml");
KronosPunchRoundRuleSummary summary = (KronosPunchRoundRuleSummary)serializer.Deserialize(textReader);
textReader.Close();
}
I have also tried thisenter code here but I get an error saying it does not expect Kronos_WFC xmlns:
public static KronosPunchRoundRuleSummary Deserialize()
{
//XmlSerializer serializer = new XmlSerializer(typeof(KronosPunchRoundRuleSummary));
//TextReader textReader;
//textReader = new StreamReader(#"c:\WSAPunchRoundRule.xml");
//KronosPunchRoundRuleSummary summary = (KronosPunchRoundRuleSummary)serializer.Deserialize(textReader);
//textReader.Close();
XmlDocument doc = new XmlDocument();
doc.Load(#"c:\WSAPunchRoundRule.xml");
string xmlcontents = doc.InnerXml;
return null;
}
The xml file looks like this
`<?xml version="1.0"?>
-<Kronos_WFC TimeStamp="03/12/2013 14:59 GMT+04:00" WFCVersion="6.2.11.231" VERSION="1.0">
-<Response action="RetrieveAllForUpdate" Status="Success">
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Default Early Start" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Ramadan" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Transfer Rounding" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="true" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="false" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Workrule Rounding" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
</Response>
</Kronos_WFC>`
My Class looks like this
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Web;
using System.Xml.Serialization;
using System.Data;
using System.Dynamic;
using System.Collections;
using System.IO;
namespace Mojito.Models
{
public class KronosPunchRoundRuleSummary
{
public List<KronosPunchRoundRule> kronosPunchRoundRules { get; set; }
}
public class KronosPunchRoundRule
{
public virtual int KronosPunchRoundRuleId { get; set; }
public virtual string Name { get; set; }
public virtual string OutPunchLateChangePoint { get; set; }
public virtual string UnscheduledInGrace { get; set; }
public virtual string OutPunchEarlyInsideRound { get; set; }
public virtual string OutPunchEarlyOutsideGrace { get; set; }
public virtual string OutPunchEarlyOutsideRound { get; set; }
public virtual string UseScheduledOut { get; set; }
public virtual string InPunchLateInsideGrace { get; set; }
public virtual string InPunchLateInsideRound { get; set; }
public virtual string OutPunchLateOutsideGrace { get; set; }
public virtual string InPunchEarlyInsideGrace { get; set; }
public virtual string UnscheduledInRound { get; set; }
public virtual string InPunchEarlyChangePoint { get; set; }
public virtual string InPunchLateOutsideGrace { get; set; }
public virtual string InPunchLateOutsideRound { get; set; }
public virtual string OutPunchLateInsideGrace { get; set; }
public virtual bool IsMissedOutException { get; set; }
public virtual string TransferGrace { get; set; }
public virtual string UnscheduledOutGrace { get; set; }
public virtual string TransferRound { get; set; }
public virtual string InPunchLateChangePoint { get; set; }
public virtual string OutPunchLateInsideRound { get; set; }
public virtual string OutPunchLateOutsideRound { get; set; }
public virtual string OutPunchEarlyInsideGrace { get; set; }
public virtual string OutPunchEarlyChangePoint { get; set; }
public virtual string InPunchEarlyOutsideRound { get; set; }
public virtual string InPunchEarlyOutsideGrace { get; set; }
public virtual string UnscheduledOutRound { get; set; }
public virtual string InPunchEarlyInsideRound { get; set; }
}
}
To do it I suggest you to read XML Serializer and Deserializer Tutorials.
XML Serialization and Deserialization: Part-1
Serialize/Deserialize any object to an XML file
Hope helps. Greetings!
UPDATE:
To serialize a unknown object you must pass all object a add to the serializer to say hwo the must serialize:
public static void Save<T>(T item, string filename, IEnumerable<Type> typeList) where T : class, new()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), typeList.ToArray());
// To write to a file, create a StreamWriter object.
StreamWriter writer = null;
try
{
writer = new StreamWriter(filename);
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(writer, item, ns);
}
catch (Exception ex)
{
}
finally
{
if (writer != null)
writer.Close();
}
}
To Deserialize unknown object its the same:
public static T Load<T>(string filename, IEnumerable<Type> typeList) where T : class, new()
{
if (!File.Exists(filename))
return new T();
TextReader fileStream = null;
try
{
// Construct an instance of the XmlSerializer with the type
// of object that is being deserialized.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), typeList.ToArray());
// To read the file, create a FileStream.
fileStream = new StreamReader(filename);
return xmlSerializer.Deserialize(fileStream) as T;
// Call the Deserialize method and cast to the object type.
// return xmlSerializer.Deserialize(fileStream) as T;
}
catch (Exception ex)
{
return new T();
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
UPDATE2:
T -> is the object you want to serialize.
filname -> the path/destinaton where you whant tu save it.
IEnumerable -> is a list of Types. Only declare a IEnumerable and Add all you type you will serialize there and after pass it on the Save, Load method.
Related
I'm trying to deserialize the following xml document into a C# object:
<ns1:StockerFichiers
xmlns:ns1="http://www.foo.fr/bar/Repository"
xmlns:ns0="http://www.foo.fr/bar/Transport/">
<ns1:fichiersAStocker>
<ns0:FichierIdentifie>
<ns0:Contenu></ns0:Contenu>
<ns0:DomaineIdLocalDoc>128</ns0:DomaineIdLocalDoc>
<ns0:EstOriginal>true</ns0:EstOriginal>
<ns0:IdLocalDoc>2018-07-06T154554_70183_2</ns0:IdLocalDoc>
<ns0:PieceDynamique>false</ns0:PieceDynamique>
<ns0:GoldenSource>false</ns0:GoldenSource>
<ns0:TypeDoc>PDF</ns0:TypeDoc>
<ns0:TypeMime>application/pdf</ns0:TypeMime>
</ns0:FichierIdentifie>
</ns1:fichiersAStocker>
</ns1:StockerFichiers>
I know a lot of deserialization questions already exist, but even if some seems to be solving the same issue I face, None of what I've tried did populate my List<FichierIdentifie>.
Where I deserialize:
public void StockerFichiersXmlBase64(string fichiersAStocker)
{
//serializer
XmlRootAttribute xroot = new XmlRootAttribute();
xroot.ElementName = "StockerFichiers";
xroot.Namespace = NamespacesConstantes.NAMESPACE_SWREPOSITORY; //ns1
XmlSerializer deserializer = new XmlSerializer(typeof(StockerFichiersRoot),xroot );
//fichiersAStocker is base64 encoded
byte[] data = Convert.FromBase64String(fichiersAStocker);
StringReader stringReader = new StringReader(Encoding.UTF8.GetString(data));
//deserialization
StockerFichiersRoot deserializedFiles = (StockerFichiersRoot)deserializer.Deserialize(stringReader);
}
My current version :
// Root
[XmlRoot(ElementName = "StockerFichiers", Namespace = NamespacesConstantes.NAMESPACE_SWREPOSITORY)]
public class StockerFichiersRoot
{
[XmlElement(ElementName = "fichiersAStocker", Namespace = NamespacesConstantes.NAMESPACE_SWREPOSITORY)]
public FichiersAStocker fichiersAStocker { get; set; }
}
//sub root
public class FichiersAStocker
{
[XmlArray(ElementName = "fichiersAStocker", Namespace = NamespacesConstantes.NAMESPACE_SWREPOSITORY)]
[XmlArrayItem(ElementName = "FichierIdentifie", Namespace=NamespacesConstantes.NAMESPACE_MSS_TRANSPORT)]
public List<FichierIdentifie> FichiersIdentifie { get; set; }
}
public class FichierIdentifie
{
[XmlElement(Namespace = NamespacesConstantes.NAMESPACE_TRANSPORT)]
public byte[] Contenu { get; set; }
//all fields are similar to the first one
}
And with this variation of the subroot class according to Is it possible to deserialize XML into List<T>? :
//sub root
public class FichiersAStocker
{
[XmlElement(ElementName = "FichierIdentifie", Namespace=NamespacesConstantes.NAMESPACE_MSS_TRANSPORT)]
public List<FichierIdentifie> FichiersIdentifie { get; set; }
}
I've also tried to remove the class FichiersAStocker (the sub root), to put the List<FichierIdentifie> in the root class, with both [xmlArray..] and [XmlElement] variations but with no success.
I always get an object with the list empty.
Try using XML2CSharp to generate class. Then try using that class or use it for debugging.
Generated code for your XML looks like this:
(You can remove unwanted properties)
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="FichierIdentifie", Namespace="http://www.foo.fr/bar/Transport/")]
public class FichierIdentifie {
[XmlElement(ElementName="Contenu", Namespace="http://www.foo.fr/bar/Transport/")]
public string Contenu { get; set; }
[XmlElement(ElementName="DomaineIdLocalDoc", Namespace="http://www.foo.fr/bar/Transport/")]
public string DomaineIdLocalDoc { get; set; }
[XmlElement(ElementName="EstOriginal", Namespace="http://www.foo.fr/bar/Transport/")]
public string EstOriginal { get; set; }
[XmlElement(ElementName="IdLocalDoc", Namespace="http://www.foo.fr/bar/Transport/")]
public string IdLocalDoc { get; set; }
[XmlElement(ElementName="PieceDynamique", Namespace="http://www.foo.fr/bar/Transport/")]
public string PieceDynamique { get; set; }
[XmlElement(ElementName="SisraGoldenSource", Namespace="http://www.foo.fr/bar/Transport/")]
public string SisraGoldenSource { get; set; }
[XmlElement(ElementName="TypeDocSisra", Namespace="http://www.foo.fr/bar/Transport/")]
public string TypeDocSisra { get; set; }
[XmlElement(ElementName="TypeMime", Namespace="http://www.foo.fr/bar/Transport/")]
public string TypeMime { get; set; }
}
[XmlRoot(ElementName="fichiersAStocker", Namespace="http://www.foo.fr/bar/Repository")]
public class FichiersAStocker {
[XmlElement(ElementName="FichierIdentifie", Namespace="http://www.foo.fr/bar/Transport/")]
public FichierIdentifie FichierIdentifie { get; set; }
}
[XmlRoot(ElementName="StockerFichiers", Namespace="http://www.foo.fr/bar/Repository")]
public class StockerFichiers {
[XmlElement(ElementName="fichiersAStocker", Namespace="http://www.foo.fr/bar/Repository")]
public FichiersAStocker FichiersAStocker { get; set; }
[XmlAttribute(AttributeName="ns1", Namespace="http://www.w3.org/2000/xmlns/")]
public string Ns1 { get; set; }
[XmlAttribute(AttributeName="ns0", Namespace="http://www.w3.org/2000/xmlns/")]
public string Ns0 { get; set; }
}
}
Really frustrating mistake that took me half a day to solve :
notice how "NamespacesConstantes.NAMESPACE_MSS_TRANSPORT" is close to "NamespacesConstantes.NAMESPACE_TRANSPORT". Add some lazy autocompletion and you can fool yourself while defining the [XmlElement...] in the "FichiersAStocker" class.
Thanks for your help Matt, I noticed this mistake while i paste some of my code on https://dotnetfiddle.net/ ! :)
I'm having difficulty parsing an XML string where the parent and child nodes have the same tag name. Obviously, I could replace the open/close tags with empty strings and parse with the code below, but that's not elegant.
I've searched and see that there are answers for how to do this with XDocument, but I specifically would like to do this with XmlSerializer (if possible).
Below is a minimal, reproducable example.
Example XML:
<AddJob>
<AddJob RequestStatus="OK" RequestMessage="Job successfuly added [testPrintServer.tif, PES_Carpet_16C_76.2 x 50.8 dpi_170517_Normal]" UUID="74ad5971-7baf-49ce-b85b-ee08188d5721" />
</AddJob>
Parsing code:
public class XmlHelper
{
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
T result;
using (var reader = new StringReader(xml))
{
result = (T)serializer.Deserialize(reader);
}
return result;
}
}
Data model:
[XmlRoot("AddJob")]
public class AddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
Calling code:
var addedJobResponse = XmlHelper.Deserialize<AddJob>(exampleXml);
Your data model doesn't match your xml structure.
Please use something like that:
[XmlRoot("AddJob")]
public class AddJob
{
[XmlElement(ElementName = "AddJob")]
public List<NestedAddJob> AddJobs { get; set; }
}
public class NestedAddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
The nested AddJob elements look like an array and you cannot have an array at the root. So add a Root class like code below :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication75
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = "<AddJob>" +
"<AddJob RequestStatus=\"OK\" RequestMessage=\"Job successfuly added [testPrintServer.tif, PES_Carpet_16C_76.2 x 50.8 dpi_170517_Normal]\" UUID=\"74ad5971-7baf-49ce-b85b-ee08188d5721\" />" +
"</AddJob>";
Root job = XmlHelper.Deserialize<Root>(xml);
}
}
public class XmlHelper
{
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
T result;
using (var reader = new StringReader(xml))
{
result = (T)serializer.Deserialize(reader);
}
return result;
}
}
[XmlRoot("AddJob")]
public class Root
{
public AddJob AddJob { get; set; }
}
public class AddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
}
My XML
<?xml version="1.0" encoding="UTF-8"?>
<teklif>
<bilgiler>
<firma>Firma Adı</firma>
<aciklama>Açıklama</aciklama>
<isim>Ad Soyad</isim>
<telefon>Telefon</telefon>
<eposta>E Posta</eposta>
<urunler>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>3,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>5,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>aas</aciklama>
<birim>2,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
</urunler>
And My Function which reads the XML file
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNodeList xmllist = doc.SelectNodes("/teklif/bilgiler/urunler");
foreach(XmlNode nod in xmllist)
{
foreach(XmlNode childNode in nod.ChildNodes)
{
// her ürünün childnode oldu
if(childNode.Name == "#text")
{
} else
{
var urun_resim = childNode.SelectSingleNode("//resimDosyasi").InnerText;
var urun_aciklama = childNode.SelectSingleNode("//aciklama").InnerText;
var urun_birim = childNode.SelectSingleNode("//birim").InnerText;
MessageBox.Show(urun_birim);
var urun_miktar = childNode.SelectSingleNode("//miktar").InnerText;
var urun_toplam = childNode.SelectSingleNode("//toplam").InnerText;
var urun = new Urun(urun_resim, urun_birim, urun_miktar, urun_aciklama);
lw_urunler.Items.Add(urun);
}
}
}
The problem is when I message box the //birim in foreach loop, it always writes the first one - 3,00((3 times). As you can see in XML, first is 3,00, the second is 5,00 and the third is 2,00 but it always writes the first one. I checked up a lot but I can't see the problem.
Try it without the //, e.g. childNode.SelectSingleNode("birim"). Two forward slashes mean the root of the XML document, and my guess is it's just always finding the first birim node starting from the root each time.
The // means to select nodes no matter where they are under the current context. Current context defaults to the root. To limit the results to those under the current child node follow this pattern (just add a dot):
var urun_resim = childNode.SelectSingleNode(".//resimDosyasi").InnerText;
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication52
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<urun> uruns = doc.Descendants("urun").Select(x => new urun() {
resimDosyasi = (string)x.Element("resimDosyasi"),
aciklama = (string)x.Element("aciklama"),
birim = (string)x.Element("birim"),
miktar = (int)x.Element("miktar"),
toplam = (string)x.Element("toplam")
}).ToList();
}
}
public class urun
{
public string resimDosyasi { get; set; }
public string aciklama { get; set; }
public string birim { get; set; }
public int miktar { get; set; }
public string toplam { get; set; }
}
}
Another approach that would increase the readability and maintenance of your code would be to map the XML schema into an object model.
Doing so, you could easly load the XML data as follows:
XmlSerializer serializer = new XmlSerializer(typeof(Teklif));
using (FileStream fileStream = new FileStream(filename, FileMode.Open))
{
Teklif result = (Teklif)serializer.Deserialize(fileStream);
}
// Object model example
[XmlRoot("teklif")]
public class Teklif
{
[XmlElement()]
public bilgiler bilgiler { get; set; }
}
public class bilgiler
{
[XmlElement()] public string firma { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string isim { get; set; }
[XmlElement()] public string telefon { get; set; }
[XmlElement()] public string eposta { get; set; }
[XmlArray()]
[XmlArrayItem("urun")]
public List<Urun> urunler { get; set; }
}
public class Urun
{
[XmlElement()] public string resimDosyasi { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string birim { get; set; }
[XmlElement()] public int miktar { get; set; }
[XmlElement()] public string toplam { get; set; }
}
It counts correctly the number of objects but returns null or zero.I have lots of a lot of classes to fill with xml content.I need an efficient method to import xml to my C# app. Is my xml file corrupt?
Xml file:
<Entitati>
<Entitate>
<nume>asd</nume>
<actiuni>25</actiuni>
<valoare>2.05</valoare>
</Entitate>
<Entitate>
<nume>fgh</nume>
<actiuni>50</actiuni>
<valoare>3.14</valoare>
</Entitate>
<Entitate>
<nume>fanel</nume>
<actiuni>35</actiuni>
<valoare>5.15</valoare>
</Entitate>
</Entitati>
Classes:
[XmlRoot("Entitati")]
public class Entitati
{
[XmlElement("Entitate")]
public List<Entitate> entitati { get; set; }
}
[XmlRoot("Entitate")]
public class Entitate
{
[XmlElement("nume")]
protected string nume { get; set; }
[XmlElement("actiuni")]
protected int actiuniDisponibile { get; set; }
[XmlElement("valoare")]
protected double valoareActiune { get; set; }
}
Main:
XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
using (FileStream fileStream = new
FileStream("C:\\Users\\batrinut\\Desktop\\Entitati.xml", FileMode.Open))
{
Entitati result = (Entitati)serializer.Deserialize(fileStream);
}
The properties in the Entitate class should not be protected.
Changing then to public should do the trick.
namespace SOTest
{
class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
using (FileStream fileStream = new FileStream("data.xml", FileMode.Open))
{
Entitati result = (Entitati)serializer.Deserialize(fileStream);
Console.ReadKey();
}
}
}
[XmlRoot("Entitati")]
public class Entitati
{
[XmlElement("Entitate")]
public List<Entitate> entitati { get; set; }
}
[XmlRoot("Entitate")]
public class Entitate
{
[XmlElement("nume")]
public string nume { get; set; }
[XmlElement("actiuni")]
public int actiuniDisponibile { get; set; }
[XmlElement("valoare")]
public double valoareActiune { get; set; }
}
}
I have the following code to deseriaze an xml string in C#.
Everything works fine and I am able to deserialize it to an object. However, the ProjectNode value is always empty.
Can someone please help me make this code work or point out what am I missing?
The sample XML has been included in the code below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DeserializeSample
{
class Program
{
static string XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><response clientos=\"Windows\" datetimepattern=\"M/d/yyyy h:mm:ss a\"><info><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?><transaction loglevel=\"0\" type=\"response\"><arguments><argument name=\"id\">1</argument><argument name=\"foredit\">True</argument><argument name=\"ScheduleOn\">Estimated</argument><argument name=\"xml\"><Project xmlns=\"http://schemas.microsoft.com/project\"><UID>0</UID><ID>0</ID></Project></argument></arguments></transaction>]]></info></response>";
static void Main(string[] args)
{
ProjectResponse projectResponse = CreateFromXml(XML, typeof(ProjectResponse)) as ProjectResponse;
}
public static object CreateFromXml(string data, Type msfRequestResponseType)
{
object projectResponse = null;
try
{
XmlSerializer deserializer = new XmlSerializer(msfRequestResponseType, "");
XmlReaderSettings settings = new XmlReaderSettings() { ProhibitDtd = true };
// We have content in the part so create xml reader and load the xml into XElement.
using (XmlReader reader = XmlReader.Create(new StringReader(data), settings))
{
projectResponse = deserializer.Deserialize(reader);
}
}
catch (Exception Ex)
{
throw;
}
return projectResponse;
}
}
[XmlRoot("response")]
[Serializable]
public class ProjectResponse
{
[XmlAnyAttribute()]
public XmlAttribute[] ResponseAttributes { get; set; }
[XmlElement("info")]
public ProjectResponseInfoTag InfoTag { get; set; }
public class ProjectResponseInfoTag
{
private string infoText = string.Empty;
[XmlText]
public string InfoText
{
get { return infoText; }
set
{
infoText = value;
Transaction = Program.CreateFromXml(infoText, typeof(ProjectTransaction)) as ProjectTransaction;
}
}
[XmlElement("transaction")]
public ProjectTransaction Transaction { get; set; }
[XmlRoot("transaction")]
public class ProjectTransaction
{
[XmlAnyAttribute]
public XmlAttribute[] TransactionAttributes { get; set; }
[XmlElement("arguments")]
public ProjectArguments Arguments { get; set; }
public class ProjectArguments
{
[XmlElement("argument")]
public List<ProjectArgument> ArgList { get; set; }
public class ProjectArgument
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlText]
public string ArgValue { get; set; }
[XmlElement("Project")]
public Project ProjectNode { get; set; }
public class Project
{
[XmlAnyElement()]
public XmlElement[] ProjectElements { get; set; }
[XmlAnyAttribute()]
public XmlAttribute[] ProjectAttributes { get; set; }
}
}
}
}
}
}
}
Xml namespaces; try
[XmlElement("Project", Namespace="http://schemas.microsoft.com/project")]