Reputation: 187
I want to convert XMl string to generic list.
My XML code :
<Color>
<t_options optionImage="1593-Black.png" optionid="4625050" RowId=1 />
<t_options optionImage="1593-Red.png" optionid="4625051" RowId=2 />
<t_options optionImage="1593-Blue.png" optionid="4625052" RowId=3 />
<t_options optionImage="1593-Green.png" optionid="4625053" RowId=4 />
</Color>
Upvotes: 0
Views: 112
Reputation: 21661
I would use XmlSerializer
, since you already have a well defined class you want to use. You just have to encapsulate the List part so that the Serializer will know what to do about the <Color>
tag:
public class t_option
{
[XmlAttribute]
public string optionImage { get; set; }
[XmlAttribute]
public string optionid { get; set; }
[XmlAttribute]
public string RowId { get; set; }
}
public class Color
{
public Color()
{
t_options = new List<t_option>();
}
[XmlElement("t_options")]
public List<t_option> t_options {get; set;}
}
public static void Main(string[] args)
{
string xml = @"<Color>
<t_options optionImage='1593-Black.png' optionid='4625050' RowId='1' />
<t_options optionImage='1593-Red.png' optionid='4625051' RowId='2' />
<t_options optionImage='1593-Blue.png' optionid='4625052' RowId='3' />
<t_options optionImage='1593-Green.png' optionid='4625053' RowId='4' />
</Color>";
XmlSerializer xser = new XmlSerializer(typeof(Color));
using (XmlReader xr = XmlReader.Create(new StringReader(xml)))
{
xr.MoveToContent();
Color c = (Color)xser.Deserialize(xr);
Console.WriteLine(c.t_options.Count);
}
// Console.WriteLine(l.Count);
Console.ReadKey();
}
Note that your XML had to be corrected - attribute values must be in quotes.
Upvotes: 0
Reputation: 96
Start with System.Xml.Linq; You'll want to load your xml file and then parse your document. For example,
var doc = XDocument.Load("file.xml");
IEnumerable<XElement> elements = doc.Descendants(tagNameHere);
And if you want to create a list, you can access those elements by doing something like this:
List<string> myElements = new List<string>();
XElement element = elements.ElementAt(0);
myElements.Add(element.Value);
This is just to get you started. I suggest you read here:
https://msdn.microsoft.com/en-us/library/system.xml.linq(v=vs.110).aspx
and do some more research on parsing xml files.
Upvotes: 1