Shortest way to deserialize XmlDocument
You could forgo the XmlReader
and use a TextReader
instead and use the TextReader
XmlSerializer.Deserialize Method
overload.
Working example:
void Main()
{
String aciResponseData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tag><bar>test</bar></tag>";
using(TextReader sr = new StringReader(aciResponseData))
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyClass));
MyClass response = (MyClass)serializer.Deserialize(sr);
Console.WriteLine(response.bar);
}
}
[System.Xml.Serialization.XmlRoot("tag")]
public class MyClass
{
public String bar;
}
How to Deserialize XML document
Here's a working version. I changed the XmlElementAttribute
labels to XmlElement
because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd();
(that function reads the whole stream and returns a string, so the Deserialize()
function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).
Here are the classes:
[Serializable()]
public class Car
{
[System.Xml.Serialization.XmlElement("StockNumber")]
public string StockNumber { get; set; }
[System.Xml.Serialization.XmlElement("Make")]
public string Make { get; set; }
[System.Xml.Serialization.XmlElement("Model")]
public string Model { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
[XmlArray("Cars")]
[XmlArrayItem("Car", typeof(Car))]
public Car[] Car { get; set; }
}
The Deserialize function:
CarCollection cars = null;
string path = "cars.xml";
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):
<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car>
</Cars>
</CarCollection>
How to deserialize xml
Try:
[XmlRoot(ElementName = "Positions", Namespace = "http://www.sample-package.org")]
public class Positions
{
[XmlElement(ElementName = "id", Namespace = "http://www.sample-package.org")]
public string id { get; set; }
[XmlElement(ElementName = "Tare_id", Namespace = "http://www.sample-package.org")]
public string Tare_id { get; set; }
}
[XmlRoot(ElementName = "Head", Namespace = "http://www.sample-package.org")]
public class OrderHeadUpload
{
[XmlElement(ElementName = "Number_confirm", Namespace = "http://www.sample-package.org")]
public string Client_id { get; set; }
[XmlElement(ElementName = "Number", Namespace = "http://www.sample-package.org")]
public string Barcode_id { get; set; }
[XmlElement(ElementName = "Positions")]
public Positions positions;
}
Use:
var order = (OrderHeadUpload)serializer.Deserialize(reader);
And you need to deserialize just onetime with OrderHeadUpload
. If you have more than one Positions, you can declare like a List<T>
How can I deserialize a XML file without defining the parent node?
As @Rand Random pointed out a possible dublicate, I looked at that question and finally git it working combining this and this.
XmlReader reader = XmlReader.Create(path);
reader.MoveToContent();
reader.ReadToDescendant("Products");
XmlSerializer serializer = new XmlSerializer(typeof(Product[]), new XmlRootAttribute() { ElementName = "Products" });
var products = (Product[])serializer.Deserialize(reader);
Deserialize xml file with mixed types
Try following xml linq :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication100
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Article article = doc.Descendants("Article").Select(x => new Article() { Stories = x.Elements("Story").Select(y => Story.ParseStory(y)).ToList() }).FirstOrDefault();
}
}
public class InputXmlModel
{
public List<Article> Articles { get; set; }
}
public class Article
{
public List<Story> Stories { get; set; }
}
public class Story
{
public string Title { get; set; }
public string Author { get; set; }
public string Lead { get; set; }
public List<Item> Items { get; set; }
public List<StoryPicture> Pictures { get; set; }
enum State
{
DEFAULT,
SUBTITLE,
}
public static Story ParseStory(XElement xStory)
{
Story story = new Story();
State state = State.DEFAULT;
Item newItem = null;
StoryPicture newPicture = null;
foreach (XElement child in xStory.Elements())
{
switch(state)
{
case State.DEFAULT :
switch (child.Name.LocalName)
{
case "Title" :
story.Title = (string)child;
break;
case "Author":
story.Author = (string)child;
break;
case "Lead":
story.Lead = (string)child;
break;
case "Subtitle":
newItem = new Item();
if (story.Items == null) story.Items = new List<Item>();
story.Items.Add(newItem);
state = State.SUBTITLE;
break;
case "Picture":
newPicture = new StoryPicture()
{
ImageHref = (string)child.Element("Image").Attribute("href"),
Credit = (string)child.Element("Credit"),
Description = (string)child.Element("Description")
};
if (story.Pictures == null) story.Pictures = new List<StoryPicture>();
story.Pictures.Add(newPicture);
break;
default:
Console.WriteLine("Error");
Console.ReadLine();
break;
}
break;
case State.SUBTITLE :
switch (child.Name.LocalName)
{
case "Body" :
newItem.ItemType = "SubTitle";
newItem.ItemText = (string)child;
break;
case "Subtitle":
newItem = new Item();
if (story.Items == null) story.Items = new List<Item>();
story.Items.Add(newItem);
break;
default:
Console.WriteLine("Error");
Console.ReadLine();
break;
}
break;
}
}
return story;
}
}
public class StoryPicture
{
public string ImageHref { get; set; }
public string Credit { get; set; }
public string Description { get; set; }
}
public class Item
{
public string ItemType { get; set; } // Possible: Body or Subtitle
public string ItemText { get; set; }
}
}
Deserialize XML into object with dynamic child elements
I've managed to resolve this using a dynamic type when deserializing.
When I deserialize ValuesRead
, it is a defined as a dynamic type.
When deserialized, it turns into an XmlNode
and from there I iterate over the node use the Name
and InnerText
values to read all the data.
How to extract the data from this xml document
We can define models that represent the Xml in the following way:
[XmlRoot("galaxy")]
public class Galaxy
{
[XmlElement("planet")]
public List<Planet> Planets { get; set; }
}
public class Planet
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("position")]
public Position Position { get; set; }
[XmlElement("speed")]
public Speed Speed { get; set; }
[XmlElement("neighbours")]
public List<Neighbour> Neighbours { get; set; }
[XmlElement("color")]
public string Color { get; set; }
[XmlElement("oncollision")]
public string OnCollision { get; set; }
}
public class Position
{
[XmlElement("x")]
public double X { get; set; }
[XmlElement("y")]
public double Y { get; set; }
[XmlElement("radius")]
public double Radius { get; set; }
}
public class Speed
{
[XmlElement("x")]
public double X { get; set; }
[XmlElement("y")]
public double Y { get; set; }
}
public class Neighbour
{
[XmlElement("planet")]
public string Name { get; set; }
}
Note how we're using the attributes to define the layout of the Xml, and map it back to the object.
With this, we're able to deserialize the Xml in the following way:
XmlSerializer serializer = new XmlSerializer(typeof(Galaxy));
using (FileStream stream = new FileStream(filePath, FileMode.Open))
{
Galaxy galaxy = (Galaxy) serializer.Deserialize(stream);
foreach (Planet planet in galaxy.Planets)
{
Console.WriteLine(planet.Name);
}
}
Output
Kobol
Namek
How to Deserialize XML document?
Use xml serialization code as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Message));
Message message = (Message)serializer.Deserialize(reader);
}
}
[XmlRoot("MESSAGE")]
public class Message
{
[XmlElement("NAME")]
public string name { get; set; }
[XmlElement("BODY")]
public Body body { get; set; }
}
public class Body
{
[XmlElement("EQPID")]
public string eqpid { get; set; }
[XmlArray("ECS")]
[XmlArrayItem("EC")]
public List<EC> ec { get; set; }
}
public class EC
{
public int ECID { get; set; }
public string ECNAME { get; set; }
public string ECDEF { get; set; }
public int ECSLL { get; set; }
public int ECSUL { get; set; }
public int ECWLL { get; set; }
public int ECWUL { get; set; }
}
}
Related Topics
How to Do a Deep Copy of an Object in .Net
An Async/Await Example That Causes a Deadlock
Deserialize Json Object into Dynamic Object Using Json.Net
Convert Generic List/Enumerable to Datatable
How to Remove All Event Handlers from an Event
Watermark/Hint/Placeholder Text in Textbox
Parallel Foreach With Asynchronous Lambda
Winform Application Ui Hangs During Long-Running Operation
C# Json.Net Convention That Follows Ruby Property Naming Conventions
How to Parse a Json String That Would Cause Illegal C# Identifiers
Embedding Dlls in a Compiled Executable
Pass Method as Parameter Using C#
Set Object Property Using Reflection
Transitioning from Windows Forms to Wpf
How to Get the Type of T from a Member of a Generic Class or Method