unable to deserialize all elements of this xml - c#

Few elements of this XML does not deserialize and but it does not throw any errors either.
<?xml version="1.0" encoding="utf-8"?>
<TrialMWordsRecord xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyList>
<MWords>
<Id>0</Id>
<Name>ListMWords1</Name>
<Type>LIST</Type>
<MyOutput>true</MyOutput>
<WordsElements>
<Words>
<Name>ListMWords1</Name>
<Value>Apple</Value>
<Type>STRING</Type>
</Words>
<Words>
<Name>ListMWords1</Name>
<Value>Mango</Value>
<Type>STRING</Type>
</Words>
<Words>
<Name>ListMWords1</Name>
<Value>Chickoo</Value>
<Type>STRING</Type>
</Words>
</WordsElements>
</MWords>
<MWords>
<Id>1</Id>
<Type>RANDOM</Type>
<MyOutput>true</MyOutput>
<WordsElements>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</WordsElements>
</MWords>
</TrialMWordsList>
</MyListRecord>
Below are my classes:
[Serializable()]
[XmlRootAttribute("MyListRecord")]
public class MyList
{
[XmlArray("MyList")]
public List<MWords> MWords
{
get;
set;
}
public static MyList Deserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(MyList));
TextReader textReader = new StreamReader(Application.StartupPath + "\\MyList.xml");
MyList resultList = (MyList)deserializer.Deserialize(textReader);
textReader.Close();
return resultList;
}
}
[Serializable()]
public class MWords
{
public int Id
{
get;
set;
}
public MWordsType Type
{
get;
set;
}
public bool MyOutput
{
get;
set;
}
public string Requirement
{
get;
set;
}
[XmlArrayItem("WordsElements")]
public List<Words> WordList
{
get;
set;
}
public static MWords Deserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(MWords));
TextReader textReader = new StreamReader(Application.StartupPath + "\\MWords.xml");
MWords mwords = (MWords)deserializer.Deserialize(textReader);
textReader.Close();
return mwords;
}
}
public class Words
{
public string Value
{
get;
set;
}
public TYPE Type
{
get;
set;
}
public string Name
{
get;
set;
}
}
Now when I deserialize this XML, if Type is LiST, the WordList gets updated, e.g. here count for WordList will be 3 but if Type is RANDOM, WordList is 0 which should actually be 1 and not 0.
Really don't know what could be the reason.

The problem is in your XML. Look at what it's like for your working case:
<WordsElements>
<Words>
<Name>ListMWords1</Name>
<Value>Apple</Value>
<Type>STRING</Type>
</Words>
<Words>
...
</Words>
<Words>
...
</Words>
</WordsElements>
Now compare that with your broken case:
<WordsElements>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</WordsElements>
You've got no Words element in there - it should be:
<WordsElements>
<Words>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</Words>
</WordsElements>
If you can't change the XML, you may need to deserialize it by hand - which probably wouldn't be too hard.
As an aside, you might want to look into writing your automatically implemented properties on one line - it's a lot more compact to write
public string Name { get; set; }
than
public string Name
{
get;
set;
}
... and it's no harder to read, IMO.

The contents of element WordsElements for type RANDOM does not wrap in <Words></Words>:
<MWords>
<Id>1</Id>
<Type>RANDOM</Type>
<MyOutput>true</MyOutput>
<WordsElements>
<Words>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</Words>
</WordsElements>
</MWords>

Related

Cannot deserialize sub-elements to list of objects

I am having problems serializing elements of an XML to a list of objects.
This is the XML:
<result>
<stats>
<numitemsfound>1451</numitemsfound>
<startfrom>0</startfrom>
</stats>
<items>
<item>
<id>1</id>
<markedfordeletion>0</markedfordeletion>
<thumbsrc>
</thumbsrc>
<thumbsrclarge>
</thumbsrclarge>
...
<datasource>65</datasource>
<data>
<amount>100</amount>
<kj>389</kj>
<kcal>92.91</kcal>
<fat_gram>0.2</fat_gram>
<fat_sat_gram>-1</fat_sat_gram>
<kh_gram>20.03</kh_gram>
</data>
<servings>
<serving>
<serving_id>386</serving_id>
<weight_gram>150</weight_gram>
</serving>
</servings>
</item>
</result>
The classes I prepared for serialization are
[XmlType("item")]
public class Item
{
[XmlAttribute("id")]
public string id { get; set; }
[XmlAttribute("markedfordeletion")]
public string markedfordeletion { get; set; }
...
[XmlAttribute("datasource")]
public string datasource { get; set; }
[XmlElement("data")]
public Data data { get; set; }
[XmlElement("servings")]
public List<Serving> servings { get; set; }
}
}
This is how I try to serialize the xml
public void ParseSearch(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Item>), new XmlRootAttribute("item"));
StringReader stringReader = new StringReader(xml);
var productList = (List<Item>)serializer.Deserialize(stringReader);
}
But I get the error ----> System.InvalidOperationException : <result xmlns=''> was not expected. Can you please help me solve this problem?
You have to use a serializer which serializes an instance of result, not of type List:
XmlSerializer serializer = new XmlSerializer(typeof(Result), new XmlRootAttribute("result")); //whatever `Result` actually is as type).
You canĀ“t serialize and de-serialize just parts of a document, either the whole one or nothing at all.
So you need a root-type:
[XmlRoot("result")]
public class Result
{
public Stats Stats {get; set;}
[XmlArray("items")]
[XmlArrayItem("item")]
public List<Item> Items { get; set; }
}

XmlSerializer Deserializing List Without namespace

Trying to deserialize List.
Im getting the following error:
System.InvalidOperationException: There is an error in XML document
(1, 2). ---> System.InvalidOperationException: was not expected.
Saw other quesitons like : {"<user xmlns=''> was not expected.} Deserializing Twitter XML but this does not solve my problem either.
This is an Xml Sample
<authorizations>
<id>111</id>
<name>Name 1</name>
<Lists>
<List>
<id>1</id>
<id>2</id>
</List>
</Lists>
</authorizations>
<authorizations>
<id>222</id>
<name>Name 2</name>
<List />
</authorizations>
<authorizations>
<id>333</id>
<name>Name 3</name>
<List />
</authorizations>
The class are created as follow:
public class Authorization
{
[XmlElement("id")]
public string Id{ get; set; }
[XmlElement("name")]
public string Name{ get; set; }
[XmlArray("Lists")]
[XmlArrayItem("List")]
public List[] Items{ get; set; }
}
public class List
{
[XmlElement("id")]
public string Id{ get; set; }
}
public class AuthorizationList
{
[XmlArray("authorizations")]
public Authorization Authorizations{ get; set; }
}
Have tried changing the list to XmlArray, XmlArrayItem or Element. but still get the same error when I deserialize.
Deserializing Code Sample:
public static T FromXml<T>(string xmlString)
{
T obj = default(T);
if (!string.IsNullOrWhiteSpace(xmlString))
{
using (var stringReader = new StringReader(xmlString))
{
var xmlSerializer = new XmlSerializer(typeof(T));
obj = (T)xmlSerializer.Deserialize(stringReader);
}
}
return obj;
}
This is ALL premised on the assumption that you have minimal control over the xml and don't have the luxury of changing that too much. As others have noted, it is not well-formed. Here is one way to get serialization to work with minimal changes to your XML and types. First, get rid of your AuthorizationList type and assign an XmlType attribute to your Authorization type (this step serves to simply pluralize the name to match how your XML has it).
[XmlType("authorizations")]
public class Authorization { ... }
public class List { ... }
Wrap your XML in the following root element:
<ArrayOfAuthorizations>
...
</ArrayOfAuthorizations>
The XML now represents a list of "authorizations" so to deserialize is just this:
List<Authorization> l = FromXml<List<Authorization>>(xml);
Another Solution:
Change the Authorizations member to be of type Authorization[] (array type rather than singular) and to have an XmlElement attribute (not XmlArray). Apply the XmlType attribute to the Authorization (as with the above solution this is to match the xml since it has the pluralized name for each array element).
[XmlType("authorizations")]
public class Authorization
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("Lists")]
[XmlArrayItem("List")]
public List[] Items { get; set; }
}
public class List
{
[XmlElement("id")]
public string Id { get; set; }
}
public class AuthorizationList
{
[XmlElement("authorizations")]
public Authorization[] Authorizations { get; set; }
}
Like before, you need to wrap your XML with the matching 'AuthorizationList' root element:
<AuthorizationList>
...
</AuthorizationList>
Then you deserialize instance of your AuthorizationList type rather that List<T> as with the previous solution.
AuthorizationList l = FromXml<AuthorizationList>(xml);
Note that the root XML element will also need to match that type name also.
<AuthorizationList>
<authorizations>
<id>111</id>
<name>Name 1</name>
<Lists>
<List>
<id>1</id>
<id>2</id>
</List>
</Lists>
</authorizations>
<authorizations>
<id>222</id>
<name>Name 2</name>
<List />
</authorizations>
<authorizations>
<id>333</id>
<name>Name 3</name>
<List />
</authorizations>
</AuthorizationList>

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>

Deserializing an XML document with the root being a list

I have an XML document provided to me externally that I need to import into my application. The document is badly written, but not something I can really do much about.
<?xml version="1.0" encoding="iso-8859-1"?>
<xml>
<Items>
<Property1 />
<Property2 />
...
</Items>
<Items>
<Property1 />
<Property2 />
...
</Items>
...
</xml>
How should I go about using the XmlSerializer for this?
It doesn't seem to matter what class setup I use, or wether I put XmlRoot(ElementName="xml") on my base class it always says that the <xml xmlns=''> is unexpected.
Edit: Added the C# code I am using
[XmlRoot(ElementName = "xml")]
public class Container
{
public List<Items> Items { get; set; }
}
public class Items
{
public short S1 { get; set; }
public short S2 { get; set; }
public short S3 { get; set; }
public short S4 { get; set; }
public short S5 { get; set; }
public short S6 { get; set; }
public short S7 { get; set; }
}
public class XMLImport
{
public Container Data{ get; private set; }
public static XMLImport DeSerializeFromFile(string fileName)
{
XMLImport import = new XMLImport();
XmlSerializer serializer = new XmlSerializer(typeof(Container));
using (StreamReader reader = new StreamReader(fileName))
import.Data = (Container)serializer.Deserialize(reader);
return import;
}
}
Say you have a class Items maps to each <Items> node:
public class Items
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
You can deserialize your list of Items like this:
var doc = XDocument.Parse(
#"<?xml version=""1.0"" encoding=""iso-8859-1""?>
<xml>
<Items>
<Property1 />
<Property2 />
</Items>
<Items>
<Property1 />
<Property2 />
</Items>
</xml>");
var serializer = new XmlSerializer(typeof(List<Items>), new XmlRootAttribute("xml"));
List<Items> list = (List<Items>)serializer.Deserialize(doc.CreateReader());
The root of your XML is not a List, the root of your xml is the <xml> node I think you are just confused by its name :)
please visit the following link, It has many good answers voted by many people.
Here is the link: How to Deserialize XML document
Error Deserializing Xml to Object - xmlns='' was not expected
Simply take off the Namespace =:
[XmlRoot("xml"), XmlType("xml")]
public class RegisterAccountResponse {...}

xml Serialization and Deserialization (hide one node header)

I have an XML file and I need to deserialize it. Without bypassing all the nodes, just deserilizing the XML file to an object.
Is it possible to hide from the result ActionGetSiteResultData or only one way
use custom serialization/deserialization?
Classes:
// root
public Result Result { get; set; }
// rows
public class Result
{
public List<ResultData> Data { get; set; }
}
//item
public class ResultData
{
[XmlElement(ElementName = "gen_info")]
public GenInfo GenInfo { get; set; }
[XmlElement(ElementName = "hosting")]
public Hosting Hosting { get; set; }
}
Result:
<Result>
<Id>1</Id>
<Data>
<ResultData> <--- REMOVE THIS
<gen_info>
<ascii-name>sadsad</ascii-name>
</gen_info>
<hosting/>
</ResultData> <--- REMOVE THIS
</Data>
</Result>
Need:
<Result>
<Id>1</Id>
<Data>
<gen_info>
<ascii-name>sadsad</ascii-name>
</gen_info>
<hosting/>
</Data>
</Result>
<Result>
<Id>2</Id>
<Data>
<gen_info>
<ascii-name>sadsad2</ascii-name>
</gen_info>
<hosting/>
</Data>
</Result>
This should do but is verbose. Try [XmlElement(ElementName = "gen_info")] on ResultData property first, if it doesn't work:
public class Result
{
[XmlIgnore]
public List<ResultData> Data { get; set; }
[XmlElement(ElementName = "gen_info")]
public ResultData[] __XmlSerializedData{
get{ return Data.ToArray();}
set{ Data = new List<ResultData>(value);}
}
}

Categories