Adding Qualified NameSpace in XML using C# - c#

How can I create XML given below in c#
<v1:Request ProductId="string" xmlns:v1="com/user/service/core/services/v1" xmlns:v11="com/user/ds/sch/pii/v1" xmlns:enum="com/uaer/schema/database/tcps/enumerations">
<v1:Name>string</v1:Name>
<v1:ID>string</v1:ID>
<v1:Code>string</v1:Code>
<v1:Key>string</v1:Key>
<v1:RequestKey>string</v1:RequestKey>
<v1:PartnerId>string</v1:PartnerId>
<v1:CustomerInfo>
<v1:Name>
<v11:Title>string</v11:Title>
<v11:Forename>string</v11:Forename>
<v11:Surname>string</v11:Surname>
<v11:Suffix>string</v11:Suffix>
</v1:Name>
<v1:Number>
<v11:Name>string</v11:Name>
<v11:Id>string</v11:Id>
</v1:Number>
</v1:Request>
Code snippet that i am using to generate the XML is this,
[XmlRoot("Request")]
public class Request{
[XmlAttribute]
public string ProductId{get;set;}
[XmlElement("Name")]
public string Name{get;set;}
[XmlElement("ID")]
public string ID{get;set;}
[XmlElement("Code")]
public string Code{get;set;}
[XmlElement("Key")]
public string Key{get;set;}
[XmlElement("RequestKey")]
public string RequestKey{get;set;}
[XmlElement("PartnerId")]
public string PartnerId{get;set;}
[XmlElement("CustomerInfo")]
public CustomerInfo CustomerInfo= new CustomerInfo();
//this(CustomerInfo) is a class which contains the reference of NAME and NUMBER class.
//NAME and NUMBER class contains their respective properties.
}
I am able to generate this XML using the above code
<Request ProductId="string" xmlns:v1="com/user/service/core/services/v1" xmlns:v11="com/user/ds/sch/pii/v1" xmlns:enum="com/uaer/schema/database/tcps/enumerations">
<Name>string</Name>
<ID>string</ID>
<Code>string</Code>
<Key>string</Key>
<RequestKey>string</RequestKey>
<PartnerId>string</PartnerId>
<CustomerInfo>
<Name>
<Title>string</Title>
<Forename>string</Forename>
<Surname>string</Surname>
<Suffix>string</Suffix>
</Name>
<Number>
<Name>string</Name>
<Id>string</Id>
</Number>
</Request>
I am adding namespace using XmlSerializerNamespaces
I am trying to consume SOAP Api and i have to pass the xml as request.

You can combine multiple namespaces by adding them to XML attributes:
[XmlRoot("Request", Namespace = "com/user/service/core/services/v1")]
public class Request
{
[XmlAttribute]
public string ProductId { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("CustomerInfo")]
public CustomerInfo CustomerInfo = new CustomerInfo();
}
public class CustomerInfo
{
[XmlElement("Name")]
public Name Name { get; set; }
}
public class Name
{
[XmlElement("Title", Namespace = "com/user/ds/sch/pii/v1")]
public string Title { get; set; }
}
The namespace prefixes are provided to the XML serializer:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("v1", "com/user/service/core/services/v1");
ns.Add("v11", "com/user/ds/sch/pii/v1");
XmlSerializer xser = new XmlSerializer(typeof(Request));
xser.Serialize(Console.Out, new Request(), ns);

Related

Setting a XML Element Name and XML Attribute to a Class Property

I have this Class that I want to convert to an XML Element
public class Person
{
[XmlElement(ElementName = "PersonName")]
public string Name { get; set; }
}
This will display an XML
<Person>
<PersonName>Smith</PersonName>
</Person>
I want to add an attribute to the element PersonName
<Person>
<PersonName required="true">Smith</PersonName>
</Person>
How would I do that?
I think you need a special class to hold your Name property, rather than relying on string. Here is an example, using the XmlText and XmlAttribute attributes to control how the built-in XmlSerializer works:
using System.Xml.Serialization;
using System.IO;
namespace SomeNamespace
{
class Program
{
static void Main(string[] args)
{
Person me = new Person("me");
string path = "C:\\temp\\person.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (StreamWriter sw = new StreamWriter(path))
{
serializer.Serialize(sw, me);
}
}
}
public class Person
{
public Person() { } // needed for serialization
public Person(string name)
{
Name = new PersonName(name);
}
[XmlElement(ElementName = "PersonName")]
public PersonName Name { get; set; }
}
public class PersonName
{
public PersonName() { } // needed for serialization
public PersonName(string name)
{
Name = name;
}
[XmlText]
public string Name { get; set; }
[XmlAttribute] // serializes as an Attribute
public bool Required { get; set; } = true;
}
}
output (at C:\temp\person.xml; you can change Main to serialize to string and print to console if you want):
<?xml version="1.0" encoding="utf-8"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<PersonName Required="true">me</PersonName>
</Person>
If you really want your Required attribute to be serialized as the lowercase "required", you can use different properties of XmlAttribute, such as: XmlAttribute(AttributeName = "required")

Map values to class properties dynamically

this is my scenario:
I have an application that downloads xml files and extracts data from them. To achieve this I've created a xml configuration file like this:
<?xml version="1.0" encoding="utf-8" ?>
<labelsSets>
<labelsSet getUrl="https://www.address.com/services/rest/product-display.xml?expand_entities=0&limit=100000000">
<fields>
<field name="item" required="true" xPath="result/item" doGet="false" isRoot="true" />
<field name="Title" required="true" xPath="title" doGet="false" />
</fields>
</labelsSet>
</labelsSets>
Where the "field" nodes are the values that I have to extract from the downloaded xml.
So, I have to insert the data into a database and I generated class like this with EF DbContext Generator:
[Table("Winery")]
public partial class Winery
{
public Winery()
{
Wine = new HashSet<Wine>();
}
[StringLength(10)]
public string Id { get; set; }
[Required]
[StringLength(200)]
public string Name { get; set; }
public DateTime? LastUpdate { get; set; }
public virtual ICollection<Wine> Wine { get; set; }
}
Is there a way to map the extracted values from xml to db table class?
I thought to add "table" and "tableField" attributes to "field" node in configuration, but I cannot find the way to achieve the mapping between the extracted values and db classes.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
//alternate method
//DataSet ds = new DataSet();
//ds.ReadXml(FILENAME);
XmlSerializer xs = new XmlSerializer(typeof(LabelsSets));
XmlTextReader reader = new XmlTextReader(FILENAME);
LabelsSets labelSets = (LabelsSets)xs.Deserialize(reader);
}
}
}
[XmlRoot("labelsSets")]
public class LabelsSets
{
[XmlElement("labelsSet")]
public List<LabelsSet> labelSet {get;set;}
}
[XmlRoot("labelsSet")]
public class LabelsSet
{
[XmlAttribute("getUrl")]
public string getUrl {get;set;}
[XmlElement("fields")]
public Fields fields {get;set;}
}
[XmlRoot("fields")]
public class Fields
{
[XmlElement("field")]
public List<Field> fields {get;set;}
}
[XmlRoot("field")]
public class Field
{
[XmlAttribute("name")]
public string name {get;set;}
[XmlAttribute("required")]
public Boolean required {get;set;}
[XmlAttribute("xPath")]
public string xPath {get;set;}
[XmlAttribute("doGet")]
public Boolean doGet {get;set;}
[XmlAttribute("isRoot")]
public Boolean isRoot {get;set;}
}

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();

Deserialize XML to object (need to return a list of objects)

Started practicing with XML and C# and I have an error message of "There is an error in XML document (3,2)". After looking at the file, I can't see anything wrong with it (Mind you, I probably missed something since I'm a noob). I'm using a Console Application for C# right now. I'm trying to return a list of Adventurers and just a side note, the GEAR element is optional. Here is what I have so far:
XML File - Test1
<?xml version="1.0" encoding="utf-8"?>
<Catalog>
<Adventurer>
<ID>001</ID>
<Name>John Smith</Name>
<Address>123 Fake Street</Address>
<Phone>123-456-7890</Phone>
<Gear>
<Attack>
<Item>
<IName>Sword</IName>
<IPrice>15.00</IPrice>
</Item>
<Item>
<IName>Wand</IName>
<IPrice>20.00</IPrice>
</Item>
</Attack>
<Defense>
<Item>
<IName>Shield</IName>
<IPrice>5.00</IPrice>
</Item>
</Defense>
</Gear>
</Adventurer>
<Adventurer>
<ID>002</ID>
<Name>Guy noone likes</Name>
<Address>Some Big House</Address>
<Phone>666-666-6666</Phone>
<Gear></Gear>
</Adventurer>
</Catalog>
C# Classes
public class Catalog
{
List<Adventurer> Adventurers { get; set; }
}
public class Adventurer
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public Gear Gear { get; set; }
}
public class Gear
{
public List<Item> Attack { get; set; }
public List<Item> Defense { get; set; }
}
public class Item
{
public string IName { get; set; }
public decimal IPrice { get; set; }
}
Serialize Function - Where the Problem Occurs at Line 5
Catalog obj = null;
string path = #"C:\Users\Blah\Desktop\test1.xml";
XmlSerializer serializer = new XmlSerializer(typeof(Catalog));
StreamReader reader = new StreamReader(path);
obj = (Catalog)serializer.Deserialize(reader);
reader.Close();
Console.ReadLine();
The issue is the list of Adventurers in Catalog:
<?xml version="1.0" encoding="utf-8"?>
<Catalog>
<Adventurers> <!-- you're missing this -->
<Adventurer>
</Adventurer>
...
<Adventurer>
</Adventurer>
</Adventurers> <!-- and missing this -->
</Catalog>
You don't have the wrapping element for the Adventurers collection.
EDIT: By the way, I find the easiest way to build the XML structure and make sure it's compatible is to create the object(s) in C#, then run through the built-in XmlSerializer and use its XML output as a basis for any XML I create rather than forming it by hand.
First, "Adventurers" property is not public, it's inaccessible, I think that the best way to find the error is to serialize your object and then compare the result with your xml file.
Your XML doesn't quite line up with your objects... namely these two...
public string City { get; set; }
and
<Address>123 Fake Street</Address>
Change City to Address or vice versa and it should fix the problem.
Edit: Got this to work in a test project, combination of all our answers...
Add <Adventurers> tag after <Catalog> (and </Adventurers> before </Catalog>) and change
List<Adventurer> Adventurers { get; set; }
to
public List<Adventurer> Adventurers { get; set; }
and it works properly for me.
I was able to get your xml to deserialize with a couple minor changes (namely the public qualifier on Adventurer).
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace TempSandbox
{
[XmlRoot]
public class Catalog
{
[XmlElement("Adventurer")]
public List<Adventurer> Adventurers;
private readonly static Type[] myTypes = new Type[] { typeof(Adventurer), typeof(Gear), typeof(Item) };
private readonly static XmlSerializer mySerializer = new XmlSerializer(typeof(Catalog), myTypes);
public static Catalog Deserialize(string xml)
{
return (Catalog)Utils.Deserialize(mySerializer, xml, Encoding.UTF8);
}
}
[XmlRoot]
public class Adventurer
{
public int ID;
public string Name;
public string Address;
public string Phone;
[XmlElement(IsNullable = true)]
public Gear Gear;
}
[XmlRoot]
public class Gear
{
public List<Item> Attack;
public List<Item> Defense;
}
[XmlRoot]
public class Item
{
public string IName;
public decimal IPrice;
}
}
I'm using [XmlElement("Adventurer")] because the xml element names don't exactly match the class property names.
NOTE: I'm using a generic deserialization utility i already had on hand .

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