bulent ozkir
suppose i have following xml fragment:
<authors>
<author>
<firstname>john</firstname>
<lastname>doe</lastname>
</author>
<author>
<firstname>jane</firstname>
<lastname>eod</lastname>
</author>
</authors>
now, how can i loop through my collection of authors and for each author retrieve its first and last name and put them in a variable strfirst and strlast?
– – – xmlapp.cs
using system;
using system.xml;
public class xmlapp
{
public void yourmethod( string strfirst, string strlast)
{
// do something with strfirst and strlast.
// …
console.writeline( "{0}, {1}", strlast, strfirst);
}
public void processxml( string xmltext)
{
xmldocument _doc = new xmldocument( );
_doc.loadxml( xmltext);
// alternately, _doc.load( _strfilename); to read from a file.
xmlnodelist _fnames = _doc.getelementsbytagname( "firstname" );
xmlnodelist _lnames = _doc.getelementsbytagname( "lastname" );
// im assuming every firstname has a lastname in this example, your requirements may vary. //
for ( int _i = 0; _i < _fnames.count; ++_i )
{
yourmethod( _fnames[ _i].innertext,
_lnames[ _i].innertext );
}
public static void main( string[] args)
{
xmlapp _app = new xmlapp( );
// passing xml text as a string, you can also use the
// xmldocument::load( ) method to read the xml from a file.
//
_app.processxml( @" <authors>
<author>
<firstname>john</firstname>
<lastname>doe</lastname>
</author>
<author>
<firstname>jane</firstname>
<lastname>eod</lastname>
</author>
</authors> " );
}
} // end xmlapp
– – – xmlapp.cs
remember to /reference the system.xml.dll on the command-line to build xmlapp.cs:
csc.exe /r:system.xml.dll xmlapp.cs
