• English (United Kingdom)
  • Spanish (Ecuador)
Home  //  Archivo  //  Reading Xml from a String Instead of File - C# .net

Temas organizados por Fecha

Socializa o.e.!

Reading Xml from a String Instead of File - C# .net
PDF
Imprimir
Correo electrónico
Lunes 27 de Febrero de 2012 10:36

csharpIn this week I've been involved in a project using xml files and string values containing xml data. Working with xml files is not big deal because there is a lot of parsers in the market and also the .net framework has classes specifically coded to work with xml files, xsd schemes and so on, for instance XmlReader and XmlWriter in the namespace System.Xml.

The problem resides when one is working with string types which contain xml structures with no schema, it's a hard work to try to iterate through elements and nodes.

At first I was working with the XMLReader class, but when I tried to iterate through elements I had no luck. I parsed the string to xml this way.

string xmlString = "<book><Author>Peter Handcock</Author><Year>2012</Year></book>";
XmlReader reader = XmlReader.Create(new StringReader(xmlString));

Solution

I've found the solution using Linq to XML classes in this namespace System.Xml.Linq ,  specifically XDocument class and its Parse() method, then I iterated the elements using the method Descendants() which returns and IEnumerable<XElement> list, finally just iterate it with a foreach, that's it boy.

 

 
XDocument reader = XDocument.Parse(xmlString);
IEnumerable<XElement> listElements = reader.Descendants();

foreach (XElement item in listElements )
{
   Console.WriteLine(item.Name+" : "+item.Value+ "\n");
}

Output:

book : Peter Handcock2012

Author : Peter Handcock

Year : 2012

 

 

See you,

Diego Toala

TAGS: parse string to xml , c# string to xml , read xml from string c# .net read string to xml

 

Última actualización el Lunes 27 de Febrero de 2012 11:22
 

Add comment


Security code
Refresh

Scroll Up