Reading XML Files using XmlDocument

 

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" );
// I'm 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

 

come from :http://www.c-sharpcorner.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值