Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 965 Vote(s) - 3.46 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to Deserialize XML document

#11
My solution:

1. Use `Edit > Past Special > Paste XML As Classes` to get the class in your code
2. Try something like this: create a list of that class (`List<class1`>), then use the `XmlSerializer` to serialize that list to a `xml` file.
3. Now you just replace the body of that file with your data and try to `deserialize` it.

Code:

StreamReader sr = new StreamReader(@"C:\Users\duongngh\Desktop\Newfolder\abc.txt");
XmlSerializer xml = new XmlSerializer(typeof(Class1[]));
var a = xml.Deserialize(sr);
sr.Close();


NOTE: you must pay attention to the root name, don't change it. Mine is "ArrayOfClass1"
Reply

#12
How about a generic class to deserialize an XML document



//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Generic class to load any xml into a class
// used like this ...
// YourClassTypeHere InfoList = LoadXMLFileIntoClass<YourClassTypeHere>(xmlFile);

using System.IO;
using System.Xml.Serialization;

public static T LoadXMLFileIntoClass<T>(string xmlFile)
{
T returnThis;
XmlSerializer serializer = new XmlSerializer(typeof(T));
if (!FileAndIO.FileExists(xmlFile))
{
Console.WriteLine("FileDoesNotExistError {0}", xmlFile);
}
returnThis = (T)serializer.Deserialize(new StreamReader(xmlFile));
return (T)returnThis;
}

This part may, or may not be necessary. Open the XML document in Visual Studio, right click on the XML, choose properties. Then choose your schema file.

Reply

#13
# For Beginners

I found the answers here to be very helpful, that said I still struggled (just a bit) to get this working. So, in case it helps someone I'll spell out the working solution:

XML from Original Question. The xml is in a file Class1.xml, a `path` to this file is used in the code to locate this xml file.

I used the answer by @erymski to get this working, so created a file called Car.cs and added the following:

> using System.Xml.Serialization; // Added
>
> public class Car
> {
> public string StockNumber { get; set; }
> public string Make { get; set; }
> public string Model { get; set; }
> }
>
> [XmlRootAttribute("Cars")]
> public class CarCollection
> {
> [XmlElement("Car")]
> public Car[] Cars { get; set; }
> }

The other bit of code provided by @erymski ...

> using (TextReader reader = new StreamReader(path))
> {
> XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
> return (CarCollection) serializer.Deserialize(reader);
> }

... goes into your main program (Program.cs), in `static CarCollection XCar()` like this:

using System;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApp2
{
class Program
{

public static void Main()
{
var c = new CarCollection();

c = XCar();

foreach (var k in c.Cars)
{
Console.WriteLine(k.Make + " " + k.Model + " " + k.StockNumber);
}
c = null;
Console.ReadLine();

}
static CarCollection XCar()
{
using (TextReader reader = new StreamReader(@"C:\Users\SlowLearner\source\repos\ConsoleApp2\ConsoleApp2\Class1.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
return (CarCollection)serializer.Deserialize(reader);
}
}
}
}

Hope it helps :-)
Reply

#14
How about you just save the xml to a file, and use [xsd][1] to generate C# classes?

1. Write the file to disk (I named it foo.xml)
2. Generate the xsd: `xsd foo.xml`
3. Generate the C#: `xsd foo.xsd /classes`

Et voila - and C# code file that should be able to read the data via `XmlSerializer`:

XmlSerializer ser = new XmlSerializer(typeof(Cars));
Cars cars;
using (XmlReader reader = XmlReader.Create(path))
{
cars = (Cars) ser.Deserialize(reader);
}

(include the generated foo.cs in the project)


[1]:

[To see links please register here]

Reply

#15
One liner:
```
var object = (Cars)new XmlSerializer(typeof(Cars)).Deserialize(new StringReader(xmlString));
```
Reply

#16
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][1] 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>


[1]:

[To see links please register here]

Reply

#17
Kevin's anser is good, aside from the fact, that in the real world, you are often not able to alter the original XML to suit your needs.

There's a simple solution for the original XML, too:

[XmlRoot("Cars")]
public class XmlData
{
[XmlElement("Car")]
public List<Car> Cars{ get; set; }
}

public class Car
{
public string StockNumber { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}

And then you can simply call:

var ser = new XmlSerializer(typeof(XmlData));
var data = (XmlData)ser.Deserialize(XmlReader.Create(PathToCarsXml));
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through