Parsing xml text

  • Thread starter Thread starter JezB
  • Start date Start date
J

JezB

I have a string which contains some xml text (either in one long line or
split into one line per data element), eg.

"<tag1>some data</tag1><tag2>some more data</tag2>"
or
"<tag1>some data</tag1> (embedded \n
character)
<tag2>some more data</tag2>"

Does the framework provide anything to easily parse this text to get at the
tags and data elements one by one ? I could of course write my own but Im
sure there must be something already there ... I just need to find it.
 
Of course ...

Any one one of the various classes under System.Xml will accomplish exactly
this.

XmlTextReader rdr = new XmlTextReader(new StringReader("<tag1>some
data</tag1><tag2>some more data</tag2>"));

rdr.MoveToContent();

while (rdr.Read()){

//Processing here
}

XmlDocument xml = new XmlDocument();
xml.LoadXml("<tag1>some data</tag1><tag2>some more data</tag2>");

and so on ... there are several options for accomplishing this... just read
the documentation

Alex
 
Im having trouble with that because the string isnt a full xml document -
its missing the header information so I get Xml exceptions thrown. Anything
else I can try ?
 
Sorry I had 'assumed' you were working with a document. My fault :)

XmlTextReader rdr = new
XmlTextReader("<tag>sometesting</tag>",XmlNodeType.Element,null);

rdr.MoveToContent();

//Do whatever you need to with it

Debug.WriteLine(rdr.ReadOuterXml());
 
I actually did it the XmlDocument way but just padded my string with <HDR>
.... </HDR> and parsed the document 2 levels deep, which worked fine. Thanks.
 
Back
Top