1

I have found a lot of answer on this question, but they are all trying to convert the string first into file and then trying to parse it using XmlDocument doc = new XmlDocument();

I am newbie in c#. Format of my string is :

<a header = '0'> < row dc = '123' al = '45' msg = '1-st line'/> < row dc = '678' al = '8' msg = 'second-line'/> </a>

I am trying to write the pseudo code to parse it :

IF <a header> == 0
Then read from the second line to last line i.e. dc = 678 , al = 8, msg = second-line
ELSE read from the first line to last line i.e.  
  dc = 123 , al = 45, msg = 1-st line
 dc = 678 , al = 8, msg = second-line

After this i have to insert into database. While applying the above condition what will be appropriate solution to this?

Amit Pal
  • 10,604
  • 26
  • 80
  • 160
  • Have you considered using Linq to XML to perform this functionality? http://msdn.microsoft.com/en-us/vstudio/bb688087.aspx check out the "Query" section, I find Linq to XML to be a far easier way to process XML these days. – Rob Aug 21 '12 at 22:54
  • possible duplicate of [Read a XML (from a string) and get some fields - Problems reading XML](http://stackoverflow.com/questions/8401280/read-a-xml-from-a-string-and-get-some-fields-problems-reading-xml). Also, there are no "lines" in an XML file, so you should stop trying to treat them as if they exist. – Ken White Aug 21 '12 at 22:54

2 Answers2

5

You don't have to save to a file to parse XML.

var xml = "<a header='0'> <row dc='123' al='45' msg='1-st line'/> <row dc='678' al='8' msg='second-line'/> </a>";
var doc = XElement.Parse(xml);
var list = from x in doc.Descendants("row")
            select new 
            {
                dc = (int)x.Attribute("dc"),
                al = (int)x.Attribute("al"),
                msg = (string)x.Attribute("msg")
            };

This simple sample would give you a list of anonymous objects that you can then easily insert into a DB.

Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92
0

Getting started code:

   XmlNode xmlNode = doc.SelectNode("/a");
   int value = xmlNode.Attributes["header"].Value;
   XmlNodes xmlNodes = xmlNode.SelectNodes("./row");
   foreach (XmlNode rowNode in XmlNodes)
Gerhard Powell
  • 5,965
  • 5
  • 48
  • 59