0

I need to convert xml to list in a particular format and I can't get my head around how to.

Below is the structure of xml. Under 'item' there can be unknown numbers of unknown items with values.

enter image description here

How can I transform to a list like below? The class i have is as below.

enter image description here

Basically, like this. There can be any numbers of item in there.

enter image description here

And finally use it like

var items = new List<item>();

I hope someone can help me.

4
  • Are you looking to do this specifically using XmlSerializer, or are you open to using XmlDocument or XDocument? What have you tried so far? Commented Feb 28, 2014 at 16:22
  • @LB2 .. Hi I have tried both. I tried XmlSerializer. It works great if i have a class structure with all the properties as unknown1, etc. But I just don't know how to do it dynamically. Commented Feb 28, 2014 at 16:32
  • @LaurenceNyein You can control deserialization performed by XmlSerializer by means of IXmlSerializable interface (though it can be a bit of a pain). Commented Feb 28, 2014 at 16:39
  • @LB2 Thanks .. I didn't know I can do select-many thing in Linq to xDocument .. Selman22's answer works for me. Commented Feb 28, 2014 at 16:51

2 Answers 2

2

You can use LINQ to XML

var xDoc = XDocument.Load("path");
var items = xDoc.Root.Descendants("item")
            .SelectMany(x => x.Descendants()
                .Select(a => new Item
        {
            field = a.Name.ToString(),
            value = (string) a);

        }));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I didn't know to use SelectMany in Linq.
0

There are a couple ways. I prefer to serialize objects into xml and back out again.

to write to your xml file:

var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<String>));
var xmlFile = new StreamWriter("path\\to\\file.xml"));
writer.Serialize(xmlFile, FileInfo);

and then to read from it:

var readFile = new StreamReader("path\\to\\file.xml");
var reader = new System.Xml.Serialization.XmlSerializer(typeof(List<String>));
var oData = (List<String>)reader.Deserialize(readFile);

Edited to add: To use your own class, just replace List<String> with your class name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.