This is my input XML file:
<?xml version="1.0" encoding="UTF-8"?>
<hosts>
<host>
<hostId>239|BS|OWN</hostId>
<images>
<image>
<name>Pic.jpg</name>
<main>true</main>
<source>../Images/Melissa/Pic.jpg</source>
</image>
</images>
</host>
</hosts>
and this is my class used to deserialiaze that XML file:
[XmlRoot("hosts")]
public class hosts
{
[XmlElement("host")]
public List<Host> Listehosts { get; set; }
}
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlElement("images")]
public List<Image> Listeimages { get; set; }
}
public class Image
{
[XmlElement("name")]
public string name { get; set; }
[XmlElement("main")]
public string main { get; set; }
[XmlElement("source")]
public string source { get; set; }
}
And this the code of my main program:
string outputTmp = "Images.xml";
XmlSerializer deserializer = new XmlSerializer(typeof(hosts));
TextReader reader = new StreamReader(outputTmp);
object obj = deserializer.Deserialize(reader);
hosts XmlData = (hosts)obj;
reader.Close();
Console.WriteLine(XmlData.Listehosts.Count);
The problem is that always images list are empty when I execute my program.
The list of hosts is charged correctly but when I checked the list of image it contains permanently null value for all the attribute (name, main, source).
Am I missing something?
Try this :
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlArray("images")] // CHANGED
[XmlArrayItem("image", typeof(Image))] // CHANGED
public List<Image> Listeimages { get; set; }
}
There is a small mistake in your code, add an ImageCollection class with a list inside.
public class ImageCollection
{
[XmlElement("image")]
public List<Image> Listeimages { get; set; }
}
public class Host
{
[XmlElement("hostId")]
public string hostId { get; set; }
[XmlElement("images")]
public ImageCollection ImageCollection { get; set; }
}
Related
Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser
I have following XML-Data:
<?xml version="1.0"?>
<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
<e:property>
<LastChange>
<Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/">
<InstanceID val="0">
<RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/>
<Volume channel="Master" val="100"/>
<Mute channel="Master" val="0"/>
<RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/>
</InstanceID>
</Event>
</LastChange>
</e:property>
</e:propertyset>
And here are my classes:
[XmlRoot("propertyset", Namespace = "urn:schemas-upnp-org:event-1-0")]
public class EventPropertySet
{
[XmlElement("property")]
public List<EventProperty> Properties { get; set; }
}
public class EventProperty
{
[XmlElement("LastChange")]
public string LastChange { get; set; }
[XmlElement("SinkProtocolInfo")]
public string SinkProtocolInfo { get; set; }
[XmlElement("IndexerStatus")]
public string IndexerStatus { get; set; }
[XmlElement("SystemUpdateID")]
public string SystemUpdateID { get; set; }
}
Now when I try to deserialize the XML-Data 'LastChange' is always 'null'.
When I modify the class 'EventProperty' like so:
public class EventProperty
{
[XmlElement("LastChange", Namespae = "")]
public string LastChange { get; set; }
[XmlElement("SinkProtocolInfo", Namespae = "")]
public string SinkProtocolInfo { get; set; }
[XmlElement("IndexerStatus", Namespae = "")]
public string IndexerStatus { get; set; }
[XmlElement("SystemUpdateID", Namespae = "")]
public string SystemUpdateID { get; set; }
}
The deserialization throws an exception:
XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements. Line 1, position 103.
Any ideas what I should do?
Sorry, I found the problem. The data behind "LastChange" is normaly a parsed XML-Structure (like this:)
<LastChange><Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"><InstanceID val="0"><RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/><Volume channel="Master" val="100"/><Mute channel="Master" val="0"/><RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/></InstanceID></Event></LastChange>
Now when I don't do the "DeParse" with WebUtility.HtmlDecode, everythings works fine.
<TotalRecords ItineraryCount='1' >
<Recs ItineraryNumber="1" >
<Amount>516.6</Amount>
<TravelTime>940</TravelTime>
<FSegment>
<OutProperty>
<Segment No="1">
<Name>Ronald</Name>
<City>London</City>
<Country>United Kingdom</Country>
</Segment>
<Segment No="2">
<Name>Richard</Name>
<City>
London
</City>
<Country>United Kingdom</Country>
</Segment>
</OutProperty>
</FSegment>
</Recs>
</TotalRecords >
I am serializing xml to object of TotalRecords Class. It works fine when there are more than one segment in the OutProperty but in case of one segment it doesn't serialize into list property.
I have also tried with [XmlArray("")] and [XMlArrayItem("")] but it doesn't work. Anyone have idea?
public class TotalRecords
{
public Recs recs { get; set; }
public string ItineraryCount { get; set; }
}
public partial class Recs
{
public string amountField { get; set; }
public string travelTimeField { get; set; }
public FSegment fSegmentField { get; set; }
public string itineraryNumberField { get; set; }
}
public class FSegment
{
public List<Segment> OutProperty {get;set;}
}
public class Segment
{
public string nameField { get; set; }
public string cityField { get; set; }
public string countryField { get; set; }
}
Try to use the following for your Classes and their Properties:
[DataContract]
public class Contact
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
Hacking like this helps in many cases, perhaps in your too (converting List to array):
public class FSegment
{
[XmlIgnore]
public List<Segment> OutProperty {get;set;}
[XmlArray("OutProperty");
public Segment[] _OutProperty
{
get { return OutProperty.ToArray(); }
set { OutProperty = new List<Segment>(value); }
}
}
I am not exactly sure how your provided class definition worked previously without any XML attribute/element definitions since your variable names are not the same as the XML identifiers, meaning that the serialization wouldn't populate the properties that it couldn't find a name for.
Nether the less, the main issue here is that you are trying to put a list into a normal property.
From the XML provided, OutProperty is a single sub element of FSegment and Segment is an array of sub elements of OutProperty, but in your provided code, you tried to make Segment an array sub element of FSegment.
The correct structure of the class definition should be as follows (also including the XML definitions)
[System.Xml.Serialization.XmlRoot(ElementName="TotalRecords")]
public class TotalRecords
{
[System.Xml.Serialization.XmlElement(ElementName="Recs")]
public Recs recs { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "ItineraryCount")]
public string ItineraryCount { get; set; }
}
public partial class Recs
{
[System.Xml.Serialization.XmlElement(ElementName = "Amount")]
public string amountField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "TravelTime")]
public string travelTimeField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "FSegment")]
public FSegment fSegmentField { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "ItineraryNumber")]
public string itineraryNumberField { get; set; }
}
public class FSegment
{
[System.Xml.Serialization.XmlElement(ElementName = "OutProperty")]
public SegmentList OutProperty { get; set; }
}
public class SegmentList
{
[System.Xml.Serialization.XmlElement(ElementName = "Segment")]
public List<Segment> segmentField { get; set; }
}
public class Segment
{
[System.Xml.Serialization.XmlElement(ElementName = "Name")]
public string nameField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "City")]
public string cityField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "Country")]
public string countryField { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "No")]
public int segmentNoField { get; set; }
}
Please note that in the above structure, Segment is a list object under the OutProperty object, which resides under the FSegment object.
Using this class structure to load your XML produces the (assumed) correct data in the created objects.
Using the XML definitions allows you to decouple the actual names of class properties from what they are called in the XML data. This allows you to changes the one or the other without affecting the other one, which is useful when you don't control the creation of the XML data.
If you don't want all the XML definitions in your code, change the names of the classes so that you can name your properties the same as what they are called in the XML file. That will allow you couple everything directly
I'm attempting to deserialize this XML file into an object
<?xml version="1.0" encoding="utf-8" ?>
<rules version="3">
<emie>
<domain>msdn.microsoft.com</domain>
<domain exclude="false">
bing.com
<path exclude="true">images</path>
</domain>
<domain exclude="true">
news.msn.com
<path exclude="false">pop-culture</path>
</domain>
<domain>timecard</domain>
<domain>tar</domain>
</emie>
</rules>
I have my objects laid out like so
[XmlRoot("rules")]
public class Rules {
[XmlAttribute("version")]
public string Version { get; set; }
[XmlElement("emie")]
public EMIE EMIE { get; set; }
}
public class EMIE {
[XmlArrayItem("Domain")]
public List<Domain> Domains { get; set; }
}
public class Domain {
[XmlAttribute("exclude")]
public bool Exclude { get; set; }
[XmlText]
public string Value { get; set; }
[XmlArrayItem("Path")]
public List<Path> Paths { get; set; }
}
public class Path {
[XmlAttribute]
public bool Exclude { get; set; }
[XmlText]
public string Value { get; set; }
}
And am using this code to deserialize it
static void Main(string[] args) {
XmlSerializer serializer = new XmlSerializer(typeof(Rules));
using (FileStream stream = new FileStream("EM.xml", FileMode.Open)) {
Rules xml = (Rules)serializer.Deserialize(stream);
foreach (Domain d in xml.EMIE.Domains) {
Console.WriteLine(d.Value);
foreach (EnterpriseModeModel.Path p in d.Paths) {
Console.WriteLine(p.Value);
}
}
}
Console.ReadLine();
}
However, my rules.EMIE.Domains object is always empty. When I debug I can see my stream object has a length so it's properly picking up the data in the file but it never fills up the object like I expect it to.
Change the declaration of EMIE as follows
public class EMIE
{
[XmlElement("domain")]
public List<Domain> Domains { get; set; }
}
I saw few topics but no one looks like my problem.
Here is my class:
namespace Framework.Cielo.Models
{
[XmlRoot("transacao", Namespace = "http://ecommerce.cbmp.com.br")]
public class TransactionResponse
{
[XmlAttribute("id")]
public string ID { get; set; }
[XmlAttribute("versao")]
public string Version { get; set; }
[XmlElement("tid")]
public string tid { get; set; }
[XmlElement("pan")]
public string pan { get; set; }
[XmlElement("dados-pedido")]
public EstablishmentOrder Order { get; set; }
[XmlElement("forma-pagamento")]
public PaymentMethod PaymentMethod { get; set; }
[XmlElement("status")]
public TransactionStatusEnum Status { get; set; }
[XmlElement("url-retorno")]
public string ReturnUrl { get; set; }
[XmlElement("autenticacao")]
public Authentication Authentication { get; set; }
}
}
and here is the authentication class
namespace Framework.Cielo.Models
{
[XmlRoot("autenticacao")]
public class Authentication
{
[XmlElement("codigo")]
public int Code { get; set; }
[XmlElement("mensagem")]
public string Message { get; set; }
[XmlIgnore]
public DateTime Date { get; set; }
[XmlElement("data-hora")]
public string FormattedDate
{
get
{
return Date.ToString("yyyy-MM-ddTHH:mm:ss");
}
set
{
DateTime kdc = DateTime.MinValue;
DateTime.TryParse(value, out kdc);
Date = kdc;
}
}
[XmlElement("valor")]
public int Value { get; set; }
[XmlElement("lr")]
public int SecurityLevel { get; set; }
[XmlElement("arp")]
public object arp { get; set; }
[XmlElement("nsu")]
public object nsu { get; set; }
}
}
Here is how I deserialize:
string serializado = File.ReadAllText("req.xml");
var stringReader = new System.IO.StringReader(serializado);
var serializer = new XmlSerializer(typeof(TransactionResponse));
TransactionResponse preAuthResponse = serializer.Deserialize(stringReader) as TransactionResponse;
and here is my XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<transacao versao="1.3.0" id="100" xmlns="http://ecommerce.cbmp.com.br">
<tid>10069930690A16DF1001</tid>
<pan>b1SQ6jpKCDt3n9C0dgD/ZkPQ1Bh+7aJESqr/CwP64P0=</pan>
<dados-pedido>
<numero>100</numero>
<valor>29900</valor>
<moeda>986</moeda>
<data-hora>2013-10-15T00:57:19.032-03:00</data-hora>
<descricao/>
<idioma>PT</idioma>
<taxa-embarque>0</taxa-embarque>
</dados-pedido>
<forma-pagamento>
<bandeira>mastercard</bandeira>
<produto>1</produto>
<parcelas>1</parcelas>
</forma-pagamento>
<status>4</status>
<autenticacao>
<codigo>4</codigo>
<mensagem>Transacao sem autenticacao</mensagem>
<data-hora>2013-10-15T00:57:19.037-03:00</data-hora>
<valor>29900</valor>
<eci>0</eci>
</autenticacao>
<autorizacao>
<codigo>4</codigo>
<mensagem>Transação autorizada</mensagem>
<data-hora>2013-10-15T00:57:19.041-03:00</data-hora>
<valor>29900</valor>
<lr>00</lr>
<arp>123456</arp>
<nsu>661215</nsu>
</autorizacao>
</transacao>
When I run this code, all the elements get right, but not ARP and NSU elements (the last 2 of autorizacao tag)
I really don't know why. This XML comes from a web service and I can't figure out why my deserialize don't work with the 2 last items but works greater with any other element.
I have tried with your code and updated following and it works.
Commented second last <autenticacao> tag.
Rename last tag <autorizacao> to <autenticacao> . May be you are getting wrong xml & last two tags are confusing so I have tried with only one tag.
In Authentication class I have changed type of ARP and NSU otherwise we are getting XMlNode type while deserializing. You can also use string instead of int.
[XmlElement("arp")]
public int arp { get; set; }
[XmlElement("nsu")]
public int nsu { get; set; }