Parse nested XML from URL - c#

I'm currently working on a .NET 4.6 console application. I need to parse a nested XML from an URL and transform the XML into an object list.
The URL for the sample XML is the following:
https://www.w3schools.com/xml/cd_catalog.xml
The XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
</CATALOG>
My corresponding C# classes look like this:
[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
[XmlElement("CD")]
List<Cd> Cds { get; set; }
}
[XmlRoot(ElementName = "CD")]
public class Cd
{
[XmlElement("TITLE")]
public string Title { get; set; }
[XmlElement("ARTIST")]
public string Artist { get; set; }
[XmlElement("COUNTRY")]
public string Country { get; set; }
[XmlElement("COMPANY")]
public string Company { get; set; }
[XmlElement("PRICE")]
public double Price { get; set; }
[XmlElement("YEAR")]
public int Year { get; set; }
}
My program class looks like this:
class Program
{
static void Main(string[] args)
{
Init();
}
public static void Init() {
var url = "https://www.w3schools.com/xml/cd_catalog.xml";
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(url);
var catalog = myXmlDocument.InnerXml.ToString();
var result = Deserialize<Catalog>(catalog);
// result is null :(
Console.ReadKey();
}
public static T Deserialize<T>(string xmlText)
{
try
{
var stringReader = new StringReader(xmlText);
var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stringReader);
}
catch (Exception ex)
{
throw;
}
}
}
So far so good, my variable catalog consists out of an XML string, but somehow the XML doesn't get parsed correctly. I always get null as a return result. Perhaps it's because of my class definitions.
What do you think, do you have an idea on how to solve this issue? To retrieve an List<Cd> instead of null.

The error is very subtle. You have done everything right, but you missed to add the public access qualifier in your Catalog class, on the list of Cd like so:
[XmlRoot(ElementName = "CATALOG")]
public class Catalog
{
[XmlElement("CD")]
public List<Cd> Cds { get; set; }
}
Since the access qualifiers default to private, the deserializer is having a hard time finding the correct property to deserialize the XML into.

List<Cd> Cds { get; set; }
Change this line to
Public List<Cd> Cds { get; set; }

Related

Casting data with a custom XML prefix to a C# model

I am trying to cast an XML document to a C# class, and for the most part, it's working fine, but in my XML I have a custom prefix, which gives me some trouble. I don't have any control over how the XML file is being generated.
<mxb:bike>Test Bike</mxb:bike>
I'm getting stuck on the mxb part since it isn't declared. My problem is that it's not declared in the XML file itself, since otherwise, it wouldn't throw the error in the first place, but I hope there is a way of solving this code side. I'm working with a .NET application, and am trying to parse an XML file to a C# model.
I'm getting the data through a post request on an API endpoint, which when I specify a model automatically converts it to that model.
My XML input is as following:
<?xml version="1.0" encoding="UTF-8"?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:gpxacx="http://www.garmin.com/xmlschemas/AccelerationExtension/v1">
<metadata>
<time>2022-09-25T12:06:47.081Z</time>
<extensions>
<mxb:bike>Test Bike</mxb:bike>
<mxb:notes>Testing</mxb:notes>
<mxb:conditions>Dry</mxb:conditions>
<mxb:track>Test Track</mxb:track>
</extensions>
</metadata>
<trk>
<trkseg>
<trkpt lat="52.914892" lon="4.776444">
<time>2022-09-25T12:06:47.081Z</time>
</trkpt>
</trkseg>
</trk>
</gpx>
My C# model looks like this:
public class GpxData
{
[XmlRoot(ElementName="extensions", Namespace="http://www.topografix.com/GPX/1/1")]
public class Extensions {
[XmlElement(ElementName="bike", Namespace="")]
public string? Bike { get; set; }
[XmlElement(ElementName="notes", Namespace="")]
public string? Notes { get; set; }
[XmlElement(ElementName="conditions", Namespace="")]
public string? Conditions { get; set; }
[XmlElement(ElementName="track", Namespace="")]
public string? Track { get; set; }
}
[XmlRoot(ElementName="metadata", Namespace="http://www.topografix.com/GPX/1/1")]
public class Metadata {
[XmlElement(ElementName="time", Namespace="http://www.topografix.com/GPX/1/1")]
public DateTime Time { get; set; }
[XmlElement(ElementName="extensions", Namespace="http://www.topografix.com/GPX/1/1")]
public Extensions Extensions { get; set; }
}
[XmlRoot(ElementName = "trkpt", Namespace = "http://www.topografix.com/GPX/1/1")]
public class Trkpt
{
[XmlElement(ElementName = "time", Namespace = "http://www.topografix.com/GPX/1/1")]
public DateTime Time { get; set; }
[XmlAttribute(AttributeName = "lat", Namespace = "")]
public double Lat { get; set; }
[XmlAttribute(AttributeName = "lon", Namespace = "")]
public double Lon { get; set; }
}
[XmlRoot(ElementName = "trkseg", Namespace = "http://www.topografix.com/GPX/1/1")]
public class Trkseg
{
[XmlElement(ElementName = "trkpt", Namespace = "http://www.topografix.com/GPX/1/1")]
public List<Trkpt> Trkpt { get; set; }
}
[XmlRoot(ElementName = "trk", Namespace = "http://www.topografix.com/GPX/1/1")]
public class Trk
{
[XmlElement(ElementName = "trkseg", Namespace = "http://www.topografix.com/GPX/1/1")]
public Trkseg Trkseg { get; set; }
}
[XmlRoot(ElementName = "gpx", Namespace = "http://www.topografix.com/GPX/1/1")]
public class Gpx
{
[XmlElement(ElementName="metadata", Namespace="http://www.topografix.com/GPX/1/1")]
public Metadata Metadata { get; set; }
[XmlElement(ElementName = "trk", Namespace = "http://www.topografix.com/GPX/1/1")]
public Trk Trk { get; set; }
[XmlAttribute(AttributeName = "creator", Namespace = "")]
public string Creator { get; set; }
}
Whenever I remove the part within the "extensions" tag, it works completely fine.
When I only remove the mxb part, and just keep the part with for example "bike" it doesn't work either.
I tried to declare the MXB prefix in the XML file itself, but since I don't have any control over the XML generation, I can't really change anything within the file, since that would only be a temporary solution, besides the fact that I don't have a schema, and as far as I know, I can't declare a prefix, without giving it a schema. Even if that would work, that wouldn't be a good solution in my case. I also tried to remove the mxb part in the XML file, and even though that solved the undeclared error issue, it would just result in the information not being cast to the model.
All the solutions I tried were related to changing something in the XML file, but that's not something I can do ;-(
I'm pretty new to XML serialzation \ deseralation, so I hope someone is able to help me! Thanks in advance.
Inspired from this answer.
You can inject a custom XmlNamespaceManager to correct missing namespace.
public class MyXmlNamespaceManager : XmlNamespaceManager
{
const string MissingNamespacePrefix = "http://missing.namespace.prefix.net/2014/";
public MyXmlNamespaceManager(XmlNameTable nameTable)
: base(nameTable)
{ }
void AddMissingNamespace(string prefix)
{
if (string.IsNullOrEmpty(prefix))
return;
string uri = MissingNamespacePrefix + prefix;
AddNamespace(prefix, uri);
}
public override bool HasNamespace(string prefix)
{
var result = base.HasNamespace(prefix);
if (!result)
AddMissingNamespace(prefix);
result = base.HasNamespace(prefix);
return result;
}
public override string LookupNamespace(string prefix)
{
var result = base.LookupNamespace(prefix);
if (result == null)
AddMissingNamespace(prefix);
result = base.LookupNamespace(prefix);
return result;
}
}
Thereby, the extension node become :
<extensions>
<mxb:bike xmlns:mxb="http://missing.namespace.prefix.net/2014/mxb">Test Bike</mxb:bike>
<mxb:notes xmlns:mxb="http://missing.namespace.prefix.net/2014/mxb">Testing</mxb:notes>
<mxb:conditions xmlns:mxb="http://missing.namespace.prefix.net/2014/mxb">Dry</mxb:conditions>
<mxb:track xmlns:mxb="http://missing.namespace.prefix.net/2014/mxb">mxb Track</mxb:track>
</extensions>
You need to adapt your model class like :
[XmlRoot(ElementName = "extensions", Namespace = "http://www.topografix.com/GPX/1/1")]
public class Extensions
{
[XmlElement(ElementName = "bike", Namespace = "http://missing.namespace.prefix.net/2014/mxb")]
public string? Bike { get; set; }
[XmlElement(ElementName = "notes", Namespace = "http://missing.namespace.prefix.net/2014/mxb")]
public string? Notes { get; set; }
[XmlElement(ElementName = "conditions", Namespace = "http://missing.namespace.prefix.net/2014/mxb")]
public string? Conditions { get; set; }
[XmlElement(ElementName = "track", Namespace = "http://missing.namespace.prefix.net/2014/mxb")]
public string? Track { get; set; }
}
Then deserialize like :
var xml = "...";
// Fix the Xml
XmlDocument xmlDoc;
using (var stream = new StringReader(xml))
{
var settings = new XmlReaderSettings();
settings.NameTable = new NameTable();
var manager = new MyXmlNamespaceManager(settings.NameTable);
XmlParserContext context = new XmlParserContext(null, manager, null, XmlSpace.Default);
using (var xmlReader = XmlReader.Create(stream, settings, context))
{
xmlDoc = new XmlDocument();
xmlDoc.Load(xmlReader);
}
}
// Deserialize
using (var stream = new MemoryStream())
{
xmlDoc.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
var serializer = new XmlSerializer(typeof(GpxData.Gpx));
var result = serializer.Deserialize(stream) as GpxData.Gpx;
Console.WriteLine(result.Metadata.Extensions.Bike);
}

deserializing a nested list in xml

I am c# silverlight beginner i am under a situation that i have thios xml code:
string xmlstring = #"<?xml version='1.0' encoding='utf-8' ?>
<par>
<name>amount</name>
<label>Amount</label>
<unit>Hundred</unit >
<comp>
<type>Combo</type>
<attributes>
<type>Integer</type>
<displayed>4</displayed>
<selected>0</selected>
<item>5</item>
</attributes>
</comp>
</par>";
** Now what is the problem ?**
In the last line when i try to debug "item" which is asssigned several value like 5 on line Debug.WriteLine(attrib.item);i just see only "5" on debugging it dont show other values. I guess i need to implement a list for it. But how to do it here that i don't know. Could some one please help me so that i will be able to have all the assigned values to item in this c# code because after this step i havce to create a GUI of it. Woudl be a big help.
Note: I cannot use ArrayList because silverligth dont support it any other lastertnative please ?
This is what you need:
[XmlRoot(ElementName = "parameter")]
public class Parameter
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("label")]
public string Label { get; set; }
[XmlElement("unit")]
public string Unit { get; set; }
[XmlElement("component")]
public Component Component { get; set; }
}
[XmlRoot(ElementName = "component")]
public class Component {
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("attributes")]
public Attributes Attributes { get; set; }
}
[XmlRoot(ElementName = "attributes")]
public class Attributes
{
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("displayed")]
public string Displayed { get; set; }
[XmlElement("selected")]
public string Selected { get; set; }
[XmlArray("items")]
[XmlArrayItem("item", typeof(string))]
public List<string> Items { get; set; }
}
class Program
{
static void Main(string[] args)
{
string xmlstring = #"<?xml version='1.0' encoding='utf-8' ?>
<parameter>
<name>max_amount</name>
<label>Max Amount</label>
<unit>Millions</unit>
<component>
<type>Combo</type>
<attributes>
<type>Integer</type>
<displayed>4</displayed>
<selected>0</selected>
<items>
<item>5</item>
<item>10</item>
<item>20</item>
<item>50</item>
</items>
</attributes>
</component >
</parameter>";
XmlSerializer deserializer = new XmlSerializer(typeof(Parameter));
XmlReader reader = XmlReader.Create(new StringReader(xmlstring));
Parameter parameter = (Parameter)deserializer.Deserialize(reader);
Console.WriteLine("Type: {0}", parameter.Component.Attributes.Type);
Console.WriteLine("Displayed: {0}", parameter.Component.Attributes.Displayed);
Console.WriteLine("Selected: {0}", parameter.Component.Attributes.Selected);
Console.WriteLine("Items: ");
foreach (var item in parameter.Component.Attributes.Items)
{
Console.WriteLine("\t{0}", item);
}
Console.ReadLine();
}
}
Note small change in xmlstring, now every <item></item> is inside container:
<items>
<item>5</item>
<item>10</item>
<item>20</item>
<item>50</item>
</items>

Deserialize XML to Object Array

I'm trying to deserialize an XML file to an object array, but I'm receiving empty objects.
My question looks similar to this: How to Deserialize xml to an array of objects? but I can't seem to create a class which inherits IXmlSerializable. That said, I don't think that approach is necessary.
Am I doing something wrong?
File Object
[XmlType("file")]
public class File
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("company_name")]
public string Company_Name { get; set; }
[XmlElement("docs")]
public HashSet<doc> Docs { get; set; }
}
Doc Object
[XmlType("doc")]
public class Doc
{
[XmlElement("valA")]
public string ValA { get; set; }
[XmlElement("valB")]
public string ValB { get; set; }
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<files>
<file>
<id>12345</id>
<company_name>Apple</company_name>
<docs>
<doc>
<valA>Info</valA>
<valB>More Info</valB>
</doc>
</docs>
</file>
<file>
<id>12345</id>
<company_name>Microsoft</company_name>
<docs>
<doc>
<valA>Even More Info</valA>
<valB>Lots of it</valB>
</doc>
</docs>
</file>
</files>
Deserialization code
XmlSerializer mySerializer = new XmlSerializer(typeof(File[]), new XmlRootAttribute("files"));
using (FileStream myFileStream = new FileStream("Files.xml", FileMode.Open))
{
File[] r;
r = (File[])mySerializer.Deserialize(myFileStream);
}
You have decorated your properties with XMLAttribute but they are elements in your XML. So, change all XMLAttribute to XmlElement.
[XmlType("file")]
public class File
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("company_name")]
public string Company_Id { get; set; }
[XmlArray("docs")]
public HashSet<Doc> Docs { get; set; }
}
[XmlType("doc")]
public class Doc
{
[XmlElement("valA")]
public string ValA { get; set; }
[XmlElement("valB")]
public string ValB { get; set; }
}
Also you XML is not well formed. I guess this is typo though -
<company_name>Apple</company_id>
<company_name>Microsoft</company_id>
Ending tag should be company_name -
<company_name>Apple</company_name>
<company_name>Microsoft</company_name>
I would use xml parser..
XDocument doc=XDocument.Load(url);
File[] r=doc.Elements("file")
.Select(f=>
new File
{
Id=f.Element("id").Value,
Company_Id=f.Element("company_name").Value,
Docs=new HashSet<Docs>(
f.Elements("docs")
.Elements("doc")
.Select(d=>
new Doc
{
ValA=d.Element("valA").Value,
ValB=d.Element("valB").Value
}))
}).ToArray();

How to serialize a class to an xml structure?

How could I serialize my below class {0} to the below xml {1}.
So, the class name, property names should match to the xml.
{0}:
[Serializable]
public class ProfileSite
{
[XmlAttribute("profileId")]
public int ProfileId { get; set; }
[XmlAttribute("siteId")]
public int SiteId { get; set; }
public Link[] Links { get; set; }
public XElement Deserialize()
{
}
}
{1}:
<profileSite profileId="" siteId="">
<links>
<link>
<originalUrl></originalUrl>
<isCrawled></isCrawled>
<isBroken></isBroken>
<isHtmlPage></isHtmlPage>
<firstAppearedLevel></firstAppearedLevel>
</link>
</links>
</profileSite>
Many thanks,
[XmlRoot("profileSite")]
public class ProfileSite
{
[XmlAttribute("profileId")]
public int ProfileId { get; set; }
[XmlAttribute("siteId")]
public int SiteId { get; set; }
[XmlArray("links"), XmlArrayItem("link")]
public Link[] Links { get; set; }
}
then:
var ser = new XmlSerializer(typeof(ProfileSite));
var site = (ProfileSite) ser.Deserialize(source);
The first step is to mark up your class with the relevant Xml... attributes which control the sreialization and whether to have attributes or elements. Your requirement basically changes the case, and has properties of the main object as attributes and properties of all child Link objects as elements:
[XmlRoot("profileSite")]
public class ProfileSite
{
[XmlAttribute("profileId")]
public int ProfileId { get; set; }
[XmlAttribute("siteId")]
public int SiteId { get; set; }
[XmlArray("links"), XmlArrayItem("link")]
public Link[] Links { get; set; }
}
public class Link
{
[XmlElement("originalUrl")]
public string OriginalUrl{get;set;}
// You other props here much like the above
}
Then to serialize it use XmlSerializer.Serialize there are many overloads taking varios places to output the result. For testing you can use the Console.Out.
XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj);
You may want to add an empty namespace manager, which stops the ugly extra xmlns attributes:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("","");
XmlSerializer serializer = new XmlSerializer(typeof(ProfileSite));
serializer.Serialize(Console.Out, obj,ns);
Output of the above using this example object:
var obj = new ProfileSite{
ProfileId=1,
SiteId=2,
Links = new[]{
new Link{OriginalUrl="www.google.com" },
new Link{OriginalUrl="www.foo.com" }
}};
is this:
<?xml version="1.0" encoding="utf-8"?>
<profileSite profileId="1" siteId="2">
<links>
<link>
<originalUrl>www.google.com</originalUrl>
</link>
<link>
<originalUrl>www.foo.com</originalUrl>
</link>
</links>
</profileSite>
Finally, here's a working example for you to play around with: http://rextester.com/XCJHD55693

Deserialization Error: The XML element 'name' from namespace '' is already present in the current scope

This is my first time using XML Serialization and this is driving me absolutely nuts after 2 days of trying to troubleshoot this.
I get this error when the deserialization kicks in:
The XML element 'name' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.
The error happens on this line in my code:
Album album = (Album)serializer.Deserialize(reader);
I not sure why. There is no dup "name" node so I just don't get it. This is an XML doc received from an HttpWebResponse from a 3rd party REST API.
Here's the complete code:
My Album Class (the type I'm Deserializing to):
public class Album
{
#region Constructors
public Album()
{
}
#endregion
#region ElementConstants
public static class ElementConstants
{
public const string aID = "aid";
public const string Owner = "owner";
public const string AlbumName = "name";
public const string CoverPhotoID = "cover_pid";
public const string CreateDate = "created";
public const string LastModifiedDate = "modified";
public const string Description = "description";
public const string Location = "location";
public const string AlbumURL = "link";
public const string Size = "size";
public const string Visible = "visible";
}
#endregion ElementConstants
#region Public Properties
[XmlArray(ElementName = "photos_GetAlbums_response")]
[XmlArrayItem( "album" )]
public Album[] Albums { get; set; }
[XmlElement (ElementName = ElementConstants.AlbumName, DataType = "string")]
public string AlbumID { get; set; }
[XmlElement(ElementName = ElementConstants.aID, DataType = "int")]
public Int32 CoverPhotoID { get; set; }
[XmlElement(ElementName = ElementConstants.Owner, DataType = "string")]
public string Owner { get; set; }
[XmlElement(ElementName = ElementConstants.AlbumName, DataType = "string")]
public string AlbumName { get; set; }
[XmlElement(ElementName = ElementConstants.aID, DataType = "DateTime")]
public DateTime CreateDate { get; set; }
[XmlElement(ElementName = ElementConstants.LastModifiedDate, DataType = "DateTime")]
public DateTime LastModifiedDate { get; set; }
[XmlElement(ElementName = ElementConstants.Description, DataType = "string")]
public string Description { get; set; }
[XmlElement(ElementName = ElementConstants.Location, DataType = "string")]
public string Location { get; set; }
[XmlElement(ElementName = ElementConstants.AlbumURL, DataType = "string")]
public string Link { get; set; }
[XmlElement(ElementName = ElementConstants.Size, DataType = "size")]
public string Size { get; set; }
[XmlElement(ElementName = ElementConstants.Visible, DataType = "string")]
public string Visible { get; set; }
#endregion
}
My Serializer Class:
public class Serializer
{
public static Album CreateAlbumFromXMLDoc(XmlDocument doc)
{
// Create an instance of a serializer
var serializer = new XmlSerializer(typeof(Album));
var reader = new StringReader(doc.ToString());
// Deserialize the Xml Object and cast to type Album
Album album = (Album)serializer.Deserialize(reader);
return album;
}
}
The XML that I am trying to Deserialized (copied from the Xml Doc object being passed into the CreateAlbumFromXMLDoc method when debugging in VS):
<?xml version="1.0" encoding="UTF-8"?>
<photos_GetAlbums_response xsi:schemaLocation="http://api.example.com/1.0/ http://api.example.com/1.0/xxx.xsd" list="true">
<album>
<aid>3231990241086938677</aid>
<cover_pid>7031990241087042549</cover_pid>
<owner>1337262814</owner>
<name>LA</name>
<created>1233469624</created>
<modified>1233469942</modified>
<description>trip to LA</description>
<location>CA</location>
<link>http://www.example.com/album.php?aid=7333&id=1337262814</link>
<size>48</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086936240</aid>
<cover_pid>7031990241087005994</cover_pid>
<owner>1337262814</owner>
<name>Wall Photos</name>
<created>1230437805</created>
<modified>1233460690</modified>
<description/>
<location/>
<link>http://www.example.com/album.php?aid=3296&id=1337262814</link>
<size>34</size>
<visible>everyone</visible>
</album>
<album>
<aid>7031990241086937544</aid>
<cover_pid>7031990241087026027</cover_pid>
<owner>1337262814</owner>
<name>Mobile Uploads</name>
<created>1231984989</created>
<modified>1233460349</modified>
<description/>
<location/>
<link>http://www.example.com/album.php?aid=6300&id=1337262814</link>
<size>3</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086936188</aid>
<cover_pid>7031990241087005114</cover_pid>
<owner>1337262814</owner>
<name>Christmas 2008</name>
<created>1230361978</created>
<modified>1230362306</modified>
<description>My Album</description>
<location/>
<link>http://www.example.com/album.php?aid=5234&id=1337262814</link>
<size>50</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086935881</aid>
<cover_pid>7031990241087001093</cover_pid>
<owner>1637262814</owner>
<name>Hock</name>
<created>1229889219</created>
<modified>1229889235</modified>
<description>Misc Pics</description>
<location/>
<link>http://www.example.com/album.php?aid=4937&id=1637262814</link>
<size>1</size>
<visible>friends-of-friends</visible>
</album>
<album>
<aid>7031990241086935541</aid>
<cover_pid>7031990241086996817</cover_pid>
<owner>1637262814</owner>
<name>Test Album 2 (for work)</name>
<created>1229460455</created>
<modified>1229460475</modified>
<description>this is a test album</description>
<location/>
<link>http://www.example.com/album.php?aid=4547&id=1637262814</link>
<size>1</size>
<visible>everyone</visible>
</album>
<album>
<aid>7031990241086935537</aid>
<cover_pid>7031990241086996795</cover_pid>
<owner>1637262814</owner>
<name>Test Album (for work)</name>
<created>1229459168</created>
<modified>1229459185</modified>
<description>Testing for work</description>
<location/>
<link>http://www.example.com/album.php?aid=4493&id=1637262814</link>
<size>1</size>
<visible>friends</visible>
</album>
</photos_GetAlbums_response>
A side note: Just for the hell of it, I paste that XML into XML Notepad 2007, it tells me:
Your XML document contains no xml-stylesheet processing instruction. To provide an XSLT transform, add the following to the top of your file and edit the href attribute accordingly:
I don't think that really means it's malformed or anything but just something to note.
So..
My ultimate goal is to get pass this damn error obviously and get an array of albums back using my code above once I can get past the error. I also want to make sure my code is correct in trying to retrieve that arrray back of albums using my Album[] property in my Album class or anything else I might be missing here. I think it's pretty close and should work but it's not.
Follow-up. I've been pulling my hair out since then.
Here's the latest. I did not use some things for now (from Marc) like the Enum, etc. I might change that later. I also pulled out the datetime stuff as it just looked wierd and I did not get errors on that anway without...at least yet. The main problem now is still my damn XML.
It's still appearing to have problems with the format I guess? Unless it's covering up another problem, no clue. This is driving me fing crazy.
I now get this error when the deserialization kicks in:
Data at the root level is invalid. Line 1, position 1.
The error happens on this line in my code: GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(reader);
How I get the response into an XmL doc:
public static XmlDocument GetResponseXmlDocument(HttpWebResponse response)
{
Stream dataStream = null; // stream from WebResponse
XmlDocument doc = new XmlDocument();
if (doc == null)
{
throw new NullReferenceException("The web reponse was null");
}
// Get the response stream so we can read the body of the response
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access
StreamReader reader = new StreamReader(dataStream);
// Load response into string variable so that we can then load into an XML doc
string responseString = reader.ReadToEnd();
// Create an XML document & load it with the response data
doc.LoadXml(responseString);
// Final XML document that represents the response
return doc;
}
My Album Class & Root Level Class (thanks to help from Marc..I get it now):
namespace xxx.Entities
{
[Serializable, XmlRoot("photos_GetAlbums_response")]
public class GetAlbumsResponse
{
[XmlElement("album")]
public List<Album> Albums { get; set; }
[XmlAttribute("list")]
public bool IsList { get; set; }
}
public class Album
{
#region Constructors
public Album()
{
}
#endregion
#region ElementConstants
/// <summary>
/// Constants Class to eliminate use of Magic Strings (hard coded strings)
/// </summary>
public static class ElementConstants
{
public const string aID = "aid";
public const string Owner = "owner";
public const string AlbumName = "name";
public const string CoverPhotoID = "cover_pid";
public const string CreateDate = "created";
public const string LastModifiedDate = "modified";
public const string Description = "description";
public const string Location = "location";
public const string AlbumURL = "link";
public const string Size = "size";
public const string Visible = "visible";
}
#endregion ElementConstants
#region Public Properties
[XmlElement (ElementName = ElementConstants.aID, DataType = "string")]
public string AlbumID { get; set; }
[XmlElement(ElementName = ElementConstants.CoverPhotoID, DataType = "int")]
public Int32 CoverPhotoID { get; set; }
[XmlElement(ElementName = ElementConstants.Owner, DataType = "string")]
public string Owner { get; set; }
[XmlElement(ElementName = ElementConstants.AlbumName, DataType = "string")]
public string AlbumName { get; set; }
public string Created { get; set; }
public DateTime Modified { get; set; }
[XmlElement(ElementName = ElementConstants.Description, DataType = "string")]
public string Description { get; set; }
[XmlElement(ElementName = ElementConstants.Location, DataType = "string")]
public string Location { get; set; }
[XmlElement(ElementName = ElementConstants.AlbumURL, DataType = "string")]
public string Link { get; set; }
public string Size { get; set; }
[XmlElement(ElementName = ElementConstants.Visible, DataType = "string")]
public string Visible { get; set; }
#endregion
}
}
My Serializer Class:
namespace xxx.Utilities
{
public class Serializer
{
public static List<Album> CreateAlbumFromXMLDoc(XmlDocument doc)
{
// Create an instance of a serializer
var serializer = new XmlSerializer(typeof(Album));
var reader = new StringReader(doc.ToString());
// Deserialize the Xml Object and cast to type Album
GetAlbumsResponse album = (GetAlbumsResponse)serializer.Deserialize(reader);
return album.Albums;
}
}
}
The true XML incoming, that I am trying to Deserialize (yes it does have xmlns):
<?xml version="1.0" encoding="UTF-8"?>
<photos_GetAlbums_response xmlns="http://api.example.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://api.example.com/1.0/ http://api.example.com/1.0/xxx.xsd" list="true">
<album>
<aid>7321990241086938677</aid>
<cover_pid>7031990241087042549</cover_pid>
<owner>1124262814</owner>
<name>Album Test 1</name>
<created>1233469624</created>
<modified>1233469942</modified>
<description>Our trip</description>
<location>CA</location>
<link>http://www.example.com/album.php?aid=7733&id=1124262814</link>
<size>48</size>
<visible>friends</visible>
</album>
<album>
<aid>231990241086936240</aid>
<cover_pid>7042330241087005994</cover_pid>
<owner>1124262814</owner>
<name>Album Test 2</name>
<created>1230437805</created>
<modified>1233460690</modified>
<description />
<location />
<link>http://www.example.com/album.php?aid=5296&id=1124262814</link>
<size>34</size>
<visible>everyone</visible>
</album>
<album>
<aid>70319423341086937544</aid>
<cover_pid>7032390241087026027</cover_pid>
<owner>1124262814</owner>
<name>Album Test 3</name>
<created>1231984989</created>
<modified>1233460349</modified>
<description />
<location />
<link>http://www.example.com/album.php?aid=6600&id=1124262814</link>
<size>3</size>
<visible>friends</visible>
</album>
</photos_GetAlbums_response>
Personally, I wouldn't use constants here - they make it hard to spot errors (and since you probably aren't re-using them, don't add much). For example:
[XmlElement (ElementName = ElementConstants.AlbumName, DataType = "string")]
public string AlbumID { get; set; }
...
[XmlElement(ElementName = ElementConstants.AlbumName, DataType = "string")]
public string AlbumName { get; set; }
Looks suspect to me...
An easier approach is to write the xml you want to a file (foo.xml, say) and use:
xsd foo.xml
xsd foo.xsd /classes
Then look at foo.cs.
Here we go... note the xml was invalid (& should be &; use of undeclared xsi namespace-alias). Note also that I added an enum for the visibility, added handling for converting the long to DateTime, and added the wrapper type:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
static class Program
{
const string xml = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<photos_GetAlbums_response
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xsi:schemaLocation=""http://api.example.com/1.0/ http://api.example.com/1.0/xxx.xsd""
list=""true"">
<album>
<aid>3231990241086938677</aid>
<cover_pid>7031990241087042549</cover_pid>
<owner>1337262814</owner>
<name>LA</name>
<created>1233469624</created>
<modified>1233469942</modified>
<description>trip to LA</description>
<location>CA</location>
<link>http://www.example.com/album.php?aid=7333&id=1337262814</link>
<size>48</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086936240</aid>
<cover_pid>7031990241087005994</cover_pid>
<owner>1337262814</owner>
<name>Wall Photos</name>
<created>1230437805</created>
<modified>1233460690</modified>
<description/>
<location/>
<link>http://www.example.com/album.php?aid=3296&id=1337262814</link>
<size>34</size>
<visible>everyone</visible>
</album>
<album>
<aid>7031990241086937544</aid>
<cover_pid>7031990241087026027</cover_pid>
<owner>1337262814</owner>
<name>Mobile Uploads</name>
<created>1231984989</created>
<modified>1233460349</modified>
<description/>
<location/>
<link>http://www.example.com/album.php?aid=6300&id=1337262814</link>
<size>3</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086936188</aid>
<cover_pid>7031990241087005114</cover_pid>
<owner>1337262814</owner>
<name>Christmas 2008</name>
<created>1230361978</created>
<modified>1230362306</modified>
<description>My Album</description>
<location/>
<link>http://www.example.com/album.php?aid=5234&id=1337262814</link>
<size>50</size>
<visible>friends</visible>
</album>
<album>
<aid>7031990241086935881</aid>
<cover_pid>7031990241087001093</cover_pid>
<owner>1637262814</owner>
<name>Hock</name>
<created>1229889219</created>
<modified>1229889235</modified>
<description>Misc Pics</description>
<location/>
<link>http://www.example.com/album.php?aid=4937&id=1637262814</link>
<size>1</size>
<visible>friends-of-friends</visible>
</album>
<album>
<aid>7031990241086935541</aid>
<cover_pid>7031990241086996817</cover_pid>
<owner>1637262814</owner>
<name>Test Album 2 (for work)</name>
<created>1229460455</created>
<modified>1229460475</modified>
<description>this is a test album</description>
<location/>
<link>http://www.example.com/album.php?aid=4547&id=1637262814</link>
<size>1</size>
<visible>everyone</visible>
</album>
<album>
<aid>7031990241086935537</aid>
<cover_pid>7031990241086996795</cover_pid>
<owner>1637262814</owner>
<name>Test Album (for work)</name>
<created>1229459168</created>
<modified>1229459185</modified>
<description>Testing for work</description>
<location/>
<link>http://www.example.com/album.php?aid=4493&id=1637262814</link>
<size>1</size>
<visible>friends</visible>
</album>
</photos_GetAlbums_response>";
static void Main()
{
XmlSerializer ser = new XmlSerializer(typeof(GetAlbumsResponse));
GetAlbumsResponse response;
using (StringReader reader = new StringReader(xml))
{
response = (GetAlbumsResponse)ser.Deserialize(reader);
}
}
}
[Serializable, XmlRoot("photos_GetAlbums_response")]
public class GetAlbumsResponse
{
[XmlElement("album")]
public List<Album> Albums {get;set;}
[XmlAttribute("list")]
public bool IsList { get; set; }
}
public enum AlbumVisibility
{
[XmlEnum("")]
None,
[XmlEnum("friends")]
Friends,
[XmlEnum("friends-of-friends")]
FriendsOfFriends,
[XmlEnum("everyone")]
Everyone
}
[Serializable]
public class Album
{
static readonly DateTime epoch = new DateTime(1970, 1, 1);
static long SerializeDateTime(DateTime value)
{
return (long)((value - epoch).TotalSeconds);
}
static DateTime DeserializeDateTime(long value)
{
return epoch.AddSeconds(value);
}
[XmlElement("aid")]
public long AlbumID { get; set; }
[XmlElement("cover_pid")]
public long CoverPhotoID { get; set; }
[XmlElement("owner")]
public long Owner { get; set; }
[XmlElement("name")]
public string AlbumName { get; set; }
[XmlIgnore]
public DateTime CreateDate { get; set; }
[XmlElement("created"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public long CreateDateInt64 {
get {return SerializeDateTime(CreateDate);}
set {CreateDate = DeserializeDateTime(value);}
}
[XmlIgnore]
public DateTime LastModifiedDate { get; set; }
[XmlElement("modified"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public long LastModifiedDateInt64
{
get { return SerializeDateTime(LastModifiedDate); }
set { LastModifiedDate = DeserializeDateTime(value); }
}
[XmlElement("description")]
public string Description { get; set; }
[XmlElement("location")]
public string Location { get; set; }
[XmlElement("link")]
public string Link { get; set; }
[XmlElement("size")]
public int Size { get; set; }
[XmlElement("visible")]
public AlbumVisibility Visibility { get; set; }
}
(08 Feb) First, treating xml as a string (for reading) isn't going to cause errors.
The problem is the namespace (the xmlns without the xsi); this wasn't in the earlier xml, so I couldn't include it... basically, you need to tell the serializer about it:
[Serializable, XmlRoot("photos_GetAlbums_response",
Namespace="http://api.example.com/1.0/")]
public class GetAlbumsResponse { /* code as before */ }
[Serializable, XmlType(Namespace="http://api.example.com/1.0/")]
public class Album { /* code as before */ }
On this occasion, a constant for the namespace would make sense (since you are re-using it).
If the xml you are showing is accurate, then the links are still corrupt, though... but maybe this is just copy/paste (i.e. don't apply this change until you know it errors...): you need & (not &). Suggest some "Replace"... at the crudest level:
string fixedXml = xml.Replace("&", "&");
(although something more precise might be better - perhaps a regex)
Note that with the different data I also had to make some of the data strings (rather than long):
[XmlElement("aid")]
public string AlbumID { get; set; }
[XmlElement("cover_pid")]
public string CoverPhotoID { get; set; }
[XmlElement("owner")]
public string Owner { get; set; }
With these changes (and mostly my original code) it works.
Of course, by this point you should be thinking "I wish I'd used xsd".
Yes - album is definitely not the root node in your XML.
What I would recommend you do is create a GetAlbumsResponse class which contains a list of albums, and move your deserialize code to the wrapper class.
Basically, remove the root element from your Album class definition, and :
[XmlRoot (ElementName="GetAlbums_response")]
public class GetAlbumsResponse
{
#region Constructors
public GetAlbumsResponse()
{
}
#endregion
[XmlArray(ElementName="album")]
public List<Album> Albums{get;set;}
... deserialization code...
}
Well,
there is a link from Microsoft targeting your problem
The Xml that would work for your current code is something like this:
<Album><photos_GetAlbums_response>
<Album>
<photos_GetAlbums_response>
<Album>
<photos_GetAlbums_response> ....
A response, which has an array of Albums, where each Album has a response which is an Array of Albums...etc.
Anyway, I already helped you in your other question, and even went to the trouble of creating a full working code sample. Why did you create another question for the same problem ?
Use System.Xml.XmlDocument to parse the input. It shouldn't take more than an hour to write the code to extract the data yourself.
Ok - I coded up an example. I took a look at the Facebook API, now here is a FULL working example.
Try this:
[XmlRoot("photos_getAlbums_response", Namespace="http://api.facebook.com/1.0/")]
public class GetAlbumsResponse
{
public GetAlbumsResponse()
{
}
[XmlElement("album")]
public List<Album> Albums { get; set; }
}
public class Album
{
[XmlElement("aid")]
public long Aid{get;set;}
[XmlElement("cover_pid")]
public long CoverPid{get;set;}
[XmlElement("owner")]
public long Owner{get;set;}
[XmlElement("name")]
public string Name{get;set;}
[XmlElement("created")]
public long Created{get;set;}
[XmlElement("modified")]
public long Modified{get;set;}
[XmlElement("description")]
public string Description{get;set;}
[XmlElement("location")]
public string Location{get;set;}
[XmlElement("link")]
public string Link{get;set;}
[XmlElement("size")]
public int Size{get;set;}
[XmlElement("visible")]
public string Visible{get;set;}
public Album()
{}
}
class XmlUtils
{
public static T DeserializeFromXml<T>(string xml)
{
T result;
XmlSerializer ser = new XmlSerializer(typeof(T));
using (TextReader tr = new StringReader(xml))
{
result = (T)ser.Deserialize(tr);
}
return result;
}
}
Now.. with an xml photos_getAlbums_response from the Facebook API,
You can deserialize like this:
GetAlbumsResponse response = XmlUtils.DeserializeFromXml<GetAlbumsResponse>(xmlResponseString);
This is a really old thread but I just faced the same issue my self while tried to serialize two different list types in the same class under the same XmlArray name, something like
<Root>
<ArrayNode>
<SubnodeType1>...</SubnodeType1>
<SubnodeType1>...</SubnodeType1>
</ArrayNode>
</Root>
Or
<Root>
<ArrayNode>
<SubnodeType2>...</SubnodeType2>
<SubnodeType2>...</SubnodeType2>
</ArrayNode>
</Root>
What has worked for me was to use a class decoration like:
[XmlRoot(Namespace = "", ElementName = "Root")]
public class Root
{
[XmlArray(ElementName = "ArrayNode", Namespace = "", IsNullable = false, Order = 1)]
[XmlArrayItem("SubnodeType1")]
public List<SubnodeType1> SubnodeType1 { get; set; }
[XmlArray(ElementName = "ArrayNode", Namespace = "", IsNullable = false, Order = 2)]
[XmlArrayItem("SubnodeType2")]
public List<SubnodeType2> SubnodeType2 { get; set; }
}
Hope it help someone else :)

Categories