C# Deserialization xml file - c#

I try to deserialize xml file:
<?xml version="1.0" encoding="utf-8"?>
<XmlFile xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<OBJECTS ITEM="ItemValue" TABLE_NAME="TableExample">
</OBJECTS>
</XmlFile>
My deserialize class code looks like that:
[Serializable]
[XmlRoot("XmlFile")]
public class SerializeObject
{
[XmlAttribute("ITEM")]
public string Item { get; set; }
[XmlAttribute("TABLE_NAME")]
public string Table_Name { get; set; }
}
When I try deserialize xml file i always got no errors and Item and Table_Name equals null. Why?
Thx for replay

[XmlRoot("XmlFile")]
public class SerializableContainer
{
[XmlElement("OBJECTS")]
public SerializeObject[] Objects { get; set; }
}
public class SerializeObject
{
[XmlAttribute("ITEM")]
public string Item { get; set; }
[XmlAttribute("TABLE_NAME")]
public string Table_Name { get; set; }
}
And then you deserialize with:
var serializer = new XmlSerializer(typeof(SerializableContainer));
using (var file = File.OpenText("sample.xml"))
{
var data = (SerializableContainer)serializer.Deserialize(file);
// ...
}

leaving here a more complete example in case anyone needs: http://davidsonsousa.net/en/post/serializedeserialize-objects-to-xml-with-c
Cheers!

Related

Writing Xml Class in c#

I have a xml file like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Devices>
<Settings>
<Name>ABC</DeviceName>
<HostNic>LAN_1</HostNic>
</Settings>
</Devices>
</Configuration>
I want to deserialize this to object form. I am trying to define a class structure for the xml file like this:
class Configuration
{
[XmlElement("Address")]
public List<Devices> deviceList = new List<Devices>();
}
class Devices
{
[XmlElement("Address")]
public List<Settings> settingList = new List<Settings>();
}
class Settings
{
public string Name { get; set; }
public string HostNic { get; set; }
}
Is there any other appropriate way of defining class for this xml file?
Your Classes need some modifications, specially the attributes you have added.
[XmlRoot]
public class Configuration
{
[XmlElement("Devices")]
public List<Devices> deviceList = new List<Devices>();
}
public class Devices
{
[XmlElement("Settings")]
public List<Settings> settingList = new List<Settings>();
}
public class Settings
{
public string Name { get; set; }
public string HostNic { get; set; }
}
Then you can de-serialize the XML into the above classes:
var serializer = new XmlSerializer(typeof(Configuration));
using (System.IO.TextReader reader = new System.IO.StringReader(<Your XML String>))
{
Configuration config = (Configuration)serializer.Deserialize(reader);
}

Parse nested XML from URL

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; }

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

Get null by deserialize in C# from XML if string between tags

i need some help, i get allways null if i will deserialize a string between two xml tags.
The following example xml file:
<?xml version="1.0" encoding="utf-8" ?>
<item name='First Item' size='1'>
<Bits value='0'>
1st String
</Bits>
<Bits value='1'>
2nd String
</Bits>
</item>
And i write the following classes:
[Serializable()]
public class Bits
{
[XmlElement(ElementName = "Bits")]
public String entryString { get; set; }
[XmlAttribute("value")]
public int entryValue { get; set; }
}
[Serializable()]
[XmlRoot("item")]
public class itemsReader
{
public itemsReader()
{
_bitList = new List<Bits>();
}
[XmlElement("Bits")]
public List<Bits> _bitList { get; set; }
[XmlAttribute("name")]
public String entryName { get; set; }
[XmlAttribute("size")]
public int entrySize { get; set; }
}
Only the entryString is always null!
To readout the XML file i use the following:
itemsReader ireader = null;
String path = #"PathtoString";
XmlSerializer serializer = new XmlSerializer(typeof(itemsReader));
var reader = File.OpenText(path);
ireader = (itemsReader)serializer.Deserialize(reader);
Thanks for help!
You have decorated entryString with XmlElement attribute which will search for an element Bits inside Bits itself.
But you want inner text of Bits element. For that we have another attribute called XmlText.
So change this
[XmlElement(ElementName = "Bits")]
public String entryString { get; set; }
to
[XmlText]
public String entryString { get; set; }
i ran your code on your input and got the output, but the i saw, in the Bits class, that the property entryString has an attribute
[XmlElement(ElementName = "Bits")]
but in your xml file there is no <Bits> tags around 1st String. so i added them and got:
<?xml version="1.0"?>
<item name="First Item" size="2">
<Bits value="1">
<Bits>firstOne</Bits>
</Bits>
<Bits value="2">
<Bits>secOne</Bits>
</Bits>
</item>
and then your code worked
so you can change the xml file or get rid of the attribute. your call

Categories