XML Deserialization not deserializing element - c#

Good Afternoon,
I have the following classes
public class MaintenanceBundle
{
[XmlAttribute(AttributeName = "Required")]
public string Required { get; set; }
[XmlAttribute(AttributeName = "ID")]
public string Id { get; set; }
[XmlElement(ElementName = "Title")]
public string Title { get; set; }
[XmlElement(ElementName = "MntReason")]
public MaintenanceReason Reason { get; set; }
[XmlElement(ElementName = "Tasks")]
public MaintenanceBundleCollection Tasks { get; set; }
}
public class MaintenanceBundleCollection
{
[XmlElement(ElementName = "Task")]
public List<MaintenanceBundleTask> Tasks { get; set; }
}
public class MaintenanceReason
{
[XmlAttribute(AttributeName = "Every")]
public string Every { get; set; }
[XmlElement(ElementName = "Mileage", IsNullable = true)]
public int? Mileage { get; set; }
[XmlElement(ElementName = "Time", IsNullable = true)]
public TimeInterval TimeInterval { get; set; }
}
I'm trying to deserialize this xml to objects using these classes. Here is the XML
<MntBundle Required="Yes" ID="S08870641702009101200000">
<Title>DIRT OR DUSTY ROADS - 5000 MILES / 6 MONTHS</Title>
<MntReason Every="No">
<Mileage Unit="MILES">5000</Mileage>
</MntReason>
<Tasks>
<Task ID="4-2" />
<Task ID="4-3">
<NMVCQualifier>Drive Shaft Boots</NMVCQualifier>
<MVCQualifiers>
<Qualifier Name="Drive Type">4WD</Qualifier>
</MVCQualifiers>
</Task>
<Task ID="4-1" />
<Task ID="4-4" />
<Task ID="5-1">
<MVCQualifiers>
<Qualifier Name="Drive Type">4WD</Qualifier>
</MVCQualifiers>
</Task>
<Task ID="6-1" />
<Task ID="7-1" />
</Tasks>
</MntBundle>
For some reason I am unable to get the Mileage element inside the MntReason element. It keeps coming back as null. Any ideas what I am doing wrong? All the other elements seem to deserialize properly. I left out irrelevant classes from my post. If anyone has any pointers how I can properly retreive this value I would love to hear it. Thanks so much for any help.
Cheers,
~ck in San Diego

Untested but it should need something like the class below. I'm not sure how XmlText will behave with an integer.
public class Mileage
{
[XmlAttribute(AttributeName = "Unit")]
public string Unit {get; set;}
[XmlText]
public int Mileage {get; set;}
}

Related

Deserialize a xml file with child elements in c#

I am trying to Deserialize a xml file of this type
<?xml version="1.0" encoding="UTF-8"?>
<Network>
<ROUTES>
<ROUTE ID="RT_BALA_GLNC_R_162_154_1" DIRECTION="LEFT" ZONE="Richmond_Hill">
<ENTRANCESIGNAL>BALA_GLNC_G162</ENTRANCESIGNAL>
<EXITSIGNAL>BALA_DONS_G154</EXITSIGNAL>
<POINTENDIDS>
<POINTENDID POS="N">PT_BALA_GLNC_W11.TrackPortionConnection</POINTENDID>
<POINTENDID POS="N">PT_BALA_GLNC_W23.TrackPortionConnection</POINTENDID>
</POINTENDIDS>
</ROUTE>
<ROUTE ID="RT_BALA_ORLS_R_111_119_1" DIRECTION="RIGHT" ZONE="Richmond_Hill">
<ENTRANCESIGNAL>BALA_ORLS_G111</ENTRANCESIGNAL>
<EXITSIGNAL>BALA_ORLN_G119</EXITSIGNAL>
<POINTENDIDS>
<POINTENDID POS="N">PT_BALA_ORLS_W1.TrackPortionConnection</POINTENDID>
</POINTENDIDS>
</ROUTE>
<ROUTE ID="RT_BALA_GLNC_R_162D_154_1" DIRECTION="LEFT" ZONE="Richmond_Hill">
<ENTRANCESIGNAL>BALA_GLNC_G162D</ENTRANCESIGNAL>
<EXITSIGNAL>BALA_DONS_G154</EXITSIGNAL>
<POINTENDIDS>
<POINTENDID POS="R">PT_BALA_GLNC_W11.TrackPortionConnection</POINTENDID>
<POINTENDID POS="N">PT_BALA_GLNC_W23.TrackPortionConnection</POINTENDID>
</POINTENDIDS>
</ROUTE>
</ROUTES>
</Network>
I have tried this
class Program
{
static void Main(string[] args)
{
XmlSerializer deserializer = new XmlSerializer(typeof(Network));
TextReader reader = new StreamReader(#"xml File Location");
object obj = deserializer.Deserialize(reader);
Network XmlData = (Network)obj;
reader.Close();
Console.ReadLine();
}
}
[XmlRoot("Network")]
public class Network
{
[XmlElement("ROUTES")]
public List<ROUTE> ROUTES { get; set; }
}
public class ROUTE
{
[XmlAttribute("ID")]
public string ID { get; set; }
[XmlAttribute("DIRECTION")]
public string DIRECTION { get; set; }
[XmlElement("ENTRANCESIGNAL")]
public string ENTRANCESIGNAL { get; set; }
[XmlElement("EXITSIGNAL")]
public string EXITSIGNAL { get; set; }
[XmlElement("POINTENDIDS")]
public POINTENDIDS POINTENDIDS { get; set; }
}
public class POINTENDIDS
{
[XmlElement("POINTENDID")]
public List<POINTENDID> POINTENDID { get; set; }
}
public class POINTENDID
{
[XmlAttribute("POS")]
public string POS { get; set; }
}
I am doing it in a console application,
I started Debugging and put breakpoint on Network XmlData = (Network)obj;
I've got only 1 ROUTES and the values of "ID", "DIRECTION", "ENTRANCESIGNAL" ...etc are set to Null
being beginner in c# programming , I don't really understand what should I do !
Need help for this implementation
Fix you Network Class. The names in square brackets are case sensitive. You also need to add the Xml array attributes.
[XmlRoot("Network")]
public class Network
{
[XmlArrayItem("ROUTE")]
[XmlArray("ROUTES")]
public List<ROUTE> ROUTES { get; set; }
}
using System.Xml; //XmlDoc
using System.Xml.Linq;//XElement
using System.IO;//Path,File,Directory, Stream
Read and parse xml file:
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(XmlFilePath);
Another approach is using XElement instead:
XElement a = XElement.Load(#"c:\path\file");
Most often I prefer XElement over XmlDocument, but that's personal
If you are starting with C#, you'd need a book, and a simpler project. Streams and Xml are syntactically complex. Also, console apps are ugly, and Forms apps are not that hard to do with the graphical tools of VisualStudio.
Your C# classes are not exactly aligned with the XML file and the serializer returns only a partial result. What you can do instead if the XML structure is fixed is outlined here.
https://stackoverflow.com/a/17315863/99804
This then works as you want it to.
You will get the following auto-generated code.
Note: I have cleaned up the output to use auto-properties etc.
using System;
using System.Xml.Serialization;
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks />
[Serializable]
[XmlType(AnonymousType = true)]
[XmlRoot(Namespace = "", IsNullable = false)]
public class Network
{
/// <remarks />
[XmlArrayItem("ROUTE", IsNullable = false)]
public NetworkROUTE[] ROUTES { get; set; }
}
[Serializable]
[XmlType(AnonymousType = true)]
public class NetworkROUTE
{
[XmlAttribute]
public string DIRECTION { get; set; }
public string ENTRANCESIGNAL { get; set; }
public string EXITSIGNAL { get; set; }
[XmlAttribute]
public string ID { get; set; }
[XmlArrayItem("POINTENDID", IsNullable = false)]
public NetworkROUTEPOINTENDID[] POINTENDIDS { get; set; }
[XmlAttribute]
public string ZONE { get; set; }
}
[Serializable]
[XmlType(AnonymousType = true)]
public class NetworkROUTEPOINTENDID
{
[XmlAttribute]
public string POS { get; set; }
[XmlText]
public string Value { get; set; }
}

Deserializing XML with different Namespaces UWP

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.

Error Deserializing an Xml to Object [duplicate]

I need some help with XmlSerializer. I have to following xml fragment:
<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'>
<id>tag:blogger.com,1999:blog-4233645339430781865.archive</id>
<updated>2012-10-22T07:00:02.139+03:00</updated>
<title type='text'>Code !t</title>
<link rel='alternate' type='text/html' href='http://www.etabakov.com/'/>
<author>
<name>Емил Табаков</name>
<email>noreply#blogger.com</email>
<gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-TbRwL19G85U/AAAAAAAAAAI/AAAAAAAAFxg/NRV6ZYqd9Wg/s512-c/photo.jpg'/>
</author>
<generator version='7.00' uri='http://www.blogger.com'>Blogger</generator>
<entry>
<id>tag:blogger.com,1999:blog-4233645339430781865.post-513753811167440871</id>
<published>2012-10-12T11:22:35.759+03:00</published>
<updated>2012-10-12T11:22:35.759+03:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/blogger/2008/kind#comment'/>
<title type='text'>Great post indeed. I really like that you are prov...</title>
<content type='html'>Great post indeed. I really like that you are providing information on .NET for freshers , Being enrolled at http://www.wiziq.com/course/57-fresher-training-projects i found your information very helpful indeed. Thanks for it.</content>
<link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4233645339430781865/8317071019326278340/comments/default/513753811167440871'/>
<author>
<name>sarabjeet</name>
<uri>http://www.blogger.com/profile/11223974173581186160</uri>
<email>noreply#blogger.com</email>
<gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/>
</author>
<thr:in-reply-to href='http://www.etabakov.com/2012/06/net-guy-velocityconf-2012-day-1.html' ref='tag:blogger.com,1999:blog-4233645339430781865.post-8317071019326278340' source='http://www.blogger.com/feeds/4233645339430781865/posts/default/8317071019326278340' type='text/html'/>
<gd:extendedProperty name='blogger.itemClass' value='pid-899300522'/>
</entry>
</feed>
And I also have the following c# objects:
Feed.cs
[XmlRoot(ElementName = "feed", Namespace = "http://www.w3.org/2005/Atom"), XmlType("feed")]
public class Feed
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("author")]
public Author Author { get; set; }
[XmlElement("entry")]
public List<Entry> Entry;
}
public class Entry
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("content")]
public string Content { get; set; }
[XmlElement("published")]
public DateTime Published { get; set; }
[XmlElement("updated")]
public DateTime Updated { get; set; }
[XmlElement("category")]
public List<Category> Categories;
[XmlElement("author")]
public Author Author { get; set; }
[XmlElement(ElementName = "in-reply-to", Namespace = "thr", Type = typeof(ReplyTo), IsNullable = true)]
public ReplyTo ReplyTo { get; set; }
}
public class ReplyTo
{
[XmlAttribute("ref")]
public string Id { get; set; }
}
Everything works perfectly so far, except that ReplyTo property always stays null. I need to get the src attribute from the
I will be really happy if someone show me what I'm missing. Thanks!
The namespace you need is "http://purl.org/syndication/thread/1.0"
"thr" is just the alias - as declared by the xmlns:thr at the top.
So:
[XmlElement(ElementName = "in-reply-to", Namespace = "http://purl.org/syndication/thread/1.0", Type = typeof(ReplyTo), IsNullable = true)]
public ReplyTo ReplyTo { get; set; }

Deserialize XML with multiple namespaces to objects

I´m trying to deserialize this XML to objects in C# .NET 4.5:
<DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"
xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/">
<item id="28" parentID="19" restricted="1">
<dc:creator>Alicia Keys</dc:creator>
<dc:date>2003-01-01</dc:date>
<dc:title>Gangsta Lovin&apos; (feat. Alicia Keys)</dc:title>
</item>
</DIDL-Lite>
Code:
I´m not getting any "item" Lists. The object isn't deserialized.
MemoryStream reader = new MemmoryStream(System.Text.Encoding.Unicode.GetBytes(Result));
var ser = new XmlSerializer(typeof(DIDLLite));
DIDLLite device = (DIDLLite)ser.Deserialize(reader);
Class DIDLLite:
[XmlRoot("DIDL-Lite", Namespace = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/")]
public class DIDLLite {
DIDLLite() {
this.serviceItem = new List<ContainerItem>();
}
[System.Xml.Serialization.XmlArrayItem("item", typeof(ServiceListTypeService), IsNullable = false)]
List<ContainerItem> serviceItem = new List<ContainerItem>();
}
Class ContainerItem:
public class ContainerItem
{
[System.Xml.Serialization.XmlAttribute("id")]
public string id { get; set; }
[System.Xml.Serialization.XmlAttribute("parentID")]
public string parentID { get; set; }
[System.Xml.Serialization.XmlAttribute("restricted")]
public string restricted { get; set; }
[System.Xml.Serialization.XmlAttribute("searchable")]
public string searchable { get; set; }
public string title { get; set; }
}
You have several issues:
you define an XmlArrayItem attribute - but really, in your XML, you don't have any list of items. If you want to use an Xml array construct, you'd need to have something like this for your XML:
<DIDL-Lite .....>
<Items>
<item id="28" parentID="19" restricted="1">
......
</item>
<item id="29" parentID="19" restricted="1">
......
</item>
</Items>
</DIDL-Lite>
So you would need to have an <Items>...</Items> wrapper around your <item> elements.
You have this declaration:
[XmlArrayItem("item", typeof(ServiceListTypeService), IsNullable = false)]
but where is the ServiceListtypeService defined? I don't see any trace of it....
I simplified your code a bit - and this works just fine:
[XmlRoot("DIDL-Lite", Namespace = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/")]
public class DIDLLite
{
[XmlElement("item")]
public ContainerItem Item { get; set; }
}
public class ContainerItem
{
[XmlAttribute("id")]
public string id { get; set; }
[XmlAttribute("parentID")]
public string parentID { get; set; }
[XmlAttribute("restricted")]
public string restricted { get; set; }
[XmlAttribute("searchable")]
public string searchable { get; set; }
// you were missing these elements and their namespace
[XmlElement(Namespace = "http://purl.org/dc/elements/1.1/")]
public string creator { get; set; }
[XmlElement(Namespace = "http://purl.org/dc/elements/1.1/")]
public string date { get; set; }
[XmlElement(Namespace = "http://purl.org/dc/elements/1.1/")]
public string title { get; set; }
}
And now, when I run your code to deserialize your XML, I do get the objects filled nicely.

c#: Deserializing xml with namespaces to clr object

I need some help with XmlSerializer. I have to following xml fragment:
<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?>
<feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'>
<id>tag:blogger.com,1999:blog-4233645339430781865.archive</id>
<updated>2012-10-22T07:00:02.139+03:00</updated>
<title type='text'>Code !t</title>
<link rel='alternate' type='text/html' href='http://www.etabakov.com/'/>
<author>
<name>Емил Табаков</name>
<email>noreply#blogger.com</email>
<gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh5.googleusercontent.com/-TbRwL19G85U/AAAAAAAAAAI/AAAAAAAAFxg/NRV6ZYqd9Wg/s512-c/photo.jpg'/>
</author>
<generator version='7.00' uri='http://www.blogger.com'>Blogger</generator>
<entry>
<id>tag:blogger.com,1999:blog-4233645339430781865.post-513753811167440871</id>
<published>2012-10-12T11:22:35.759+03:00</published>
<updated>2012-10-12T11:22:35.759+03:00</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/blogger/2008/kind#comment'/>
<title type='text'>Great post indeed. I really like that you are prov...</title>
<content type='html'>Great post indeed. I really like that you are providing information on .NET for freshers , Being enrolled at http://www.wiziq.com/course/57-fresher-training-projects i found your information very helpful indeed. Thanks for it.</content>
<link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/4233645339430781865/8317071019326278340/comments/default/513753811167440871'/>
<author>
<name>sarabjeet</name>
<uri>http://www.blogger.com/profile/11223974173581186160</uri>
<email>noreply#blogger.com</email>
<gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/>
</author>
<thr:in-reply-to href='http://www.etabakov.com/2012/06/net-guy-velocityconf-2012-day-1.html' ref='tag:blogger.com,1999:blog-4233645339430781865.post-8317071019326278340' source='http://www.blogger.com/feeds/4233645339430781865/posts/default/8317071019326278340' type='text/html'/>
<gd:extendedProperty name='blogger.itemClass' value='pid-899300522'/>
</entry>
</feed>
And I also have the following c# objects:
Feed.cs
[XmlRoot(ElementName = "feed", Namespace = "http://www.w3.org/2005/Atom"), XmlType("feed")]
public class Feed
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("author")]
public Author Author { get; set; }
[XmlElement("entry")]
public List<Entry> Entry;
}
public class Entry
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("content")]
public string Content { get; set; }
[XmlElement("published")]
public DateTime Published { get; set; }
[XmlElement("updated")]
public DateTime Updated { get; set; }
[XmlElement("category")]
public List<Category> Categories;
[XmlElement("author")]
public Author Author { get; set; }
[XmlElement(ElementName = "in-reply-to", Namespace = "thr", Type = typeof(ReplyTo), IsNullable = true)]
public ReplyTo ReplyTo { get; set; }
}
public class ReplyTo
{
[XmlAttribute("ref")]
public string Id { get; set; }
}
Everything works perfectly so far, except that ReplyTo property always stays null. I need to get the src attribute from the
I will be really happy if someone show me what I'm missing. Thanks!
The namespace you need is "http://purl.org/syndication/thread/1.0"
"thr" is just the alias - as declared by the xmlns:thr at the top.
So:
[XmlElement(ElementName = "in-reply-to", Namespace = "http://purl.org/syndication/thread/1.0", Type = typeof(ReplyTo), IsNullable = true)]
public ReplyTo ReplyTo { get; set; }

Categories