brian4342
brian4342

Reputation: 1253

How to convert Xml to string array

Currently the application that I am working on returns XML into a string.

String xml = getData();

But now I need to convert this to a string array, the Xml will something like this:

<details> 
 <row> 
  <Year>2014</Year> 
  <Person>Bob</Person> 
 </row> 
 <row> 
  <Year>2013</Year> 
  <Person>Fred</Person> 
 </row> 
</details> 

Ive seen how to do this if the XML is saved in a file but this wont be an option. Any Ideas?

I would like to have something like a dictionary array or list of arrays with the values looking like this: year, year, year

person, person, person

Upvotes: 1

Views: 6179

Answers (3)

har07
har07

Reputation: 89285

You can try this way :

var doc = XDocument.Parse(xml);
var rows = from row in doc.Root.Elements("row") select row;

//array of person
var persons = rows.Select(o => (string) o.Element("Person")).ToArray();
//array of year
var years = rows.Select(o => (string)o.Element("Year")).ToArray();

If you meant to get all element inside <row> in single array, try this way :

//you can remove OrderBy part if it isn't necessary
var result = rows.SelectMany(o => o.Elements())
                 .OrderBy(o => o.Name.LocalName)
                 .Select(o => (string) o).ToArray();

Upvotes: 4

Flat Eric
Flat Eric

Reputation: 8111

Assuming that "details" is the root element of your XmlFile and the name of the file is "XMLFile1.xml", you can use this:

XmlDocument doc = new XmlDocument();
doc.Load("XMLFile1.xml");

var rows = doc.GetElementsByTagName("row").Cast<XmlElement>();
var persons = rows.SelectMany(x => x.GetElementsByTagName("Person")
    .Cast<XmlElement>()).ToArray().Select(x => x.InnerText).ToArray();
var years = rows.SelectMany(x => x.GetElementsByTagName("Year")
    .Cast<XmlElement>()).ToArray().Select(x => x.InnerText).ToArray();

And don't forget to include the Linq-namespace.

Upvotes: 0

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

As per answer given in this post

var rows = XDocument.Load("filename.xml")
                    .Root.Elements()
                    .Select(row => row.Elements()
                                      .ToDictionary(v => v.Attribute("name").Value,
                                                    v => v.Attribute("value").Value);

Upvotes: 0

Related Questions