欢迎光临
我们一直在努力

利用正则表达式将html网页数据变成Web Service-.NET教程,Web Service开发

建站超值云服务器,限时71元/月

这次的题目很简单,中国银行有一个查当天汇率的网页(http://www.bank-of-china.com/info/qpindex.shtml),不过是传统的html格式,而其又没有提供xml格式或者webservice查询。现在如果希望其他的信息系统能够随时读取其中的数据,那么方便的莫过于中行提供一个webservice接口供大家调用,这也是典型的安全的webservice应用。可惜中行没有做,那么我们能不能自己来做呢?当然可以,只要用程序分析其html网页,那么就可以很容易的读取其中的数据。文本分析,当然要看我们的"regular expression"(呵呵,其实这才是写这个程序的真实目的 — 应用正则表达式。)

中行的页面类似于:

日期:2004/09/30 有效期至2004/10/07

货币名称 现汇买入价 现钞买入价 卖出价 基准价

英镑 1488.1700

1453.1500

1492.6400

港币 105.9700

105.3300

106.2900

106.1100

美元 826.4200

821.4500

828.9000

827.6600

瑞士法郎 655.9300

641.1400

659.2200

新加坡元 488.7600

477.2600

490.2300

瑞典克朗 112.4900

109.8400

112.8300

丹麦克朗 136.5900

133.3700

137.0000

挪威克朗 121.9500

119.0800

122.3100

日元 7.4344

7.3785

7.4717

7.4519

加拿大元 650.8000

635.4800

652.7600

澳大利亚元 591.9900

578.6400

594.9600

欧元 1019.6400

1010.9600

1022.7000

1019.7000

澳门元 103.2200

102.6000

103.5300

菲律宾比索 14.6700

14.3300

14.7200

泰国铢 19.9000

19.4300

19.9600

新西兰元 553.7000

555.3600

对其代码分析后,给出了一个正则表达式,当然这个表达式还不完善,但是针对目前比较固定的中行的汇率页面来说,暂时还没有问题。

@"<tr bgcolor=#\w+ ><td height=20>(?<currency>.*)</td>\s*" +

@"<td height=20><p align=right>(?<bankbuytt>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<buynotes>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<sell>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<base>\d*.?\d*)(&nbsp)+.?</td>\s*"

然后过滤就非常简单了。我一直以为代码是最好的说明,特别是对于优雅的语言来说,因为我就不多说了,代码伺候。

这是所建webservice页面foreignexchange.asmx的代码:

using system;

using system.collections;

using system.componentmodel;

using system.data;

using system.diagnostics;

using system.web;

using system.net;

using system.web.services;

using system.xml;

using system.text;

using system.text.regularexpressions;

using system.io;

namespace chinabank

{

/// <summary>

/// summary description for foreignexchange.

/// </summary>

[webservice(namespace="http://dancefires.com/chinabank/")]

public class foreignexchange : system.web.services.webservice

{

public foreignexchange()

{

//codegen: this call is required by the asp.net web services designer

initializecomponent();

}

#region component designer generated code

//required by the web services designer

private icontainer components = null;

/// <summary>

/// required method for designer support – do not modify

/// the contents of this method with the code editor.

/// </summary>

private void initializecomponent()

{

}

/// <summary>

/// clean up any resources being used.

/// </summary>

protected override void dispose( bool disposing )

{

if(disposing && components != null)

{

components.dispose();

}

base.dispose(disposing);

}

#endregion

[webmethod]

public xmldatadocument getforeignexchangerates()

{

return getxmldoc();

}

[webmethod]

public dataset getforeignexchangeratesdataset()

{

return getxmldoc().dataset;

}

[webmethod]

public string getbankpage()

{

return getwebcontent( "http://www.bank-of-china.com/info/whjrpj.html" );

}

// private methods

private string getwebcontent( string url )

{

using( webclient client = new webclient() )

{

byte[] buffer = client.downloaddata( url );

string str = encoding.getencoding("gb2312").getstring( buffer, 0, buffer.length );

return str;

}

}

private xmldatadocument getxmldoc()

{

string webcontent = getwebcontent("http://www.bank-of-china.com/info/whjrpj.html");

// prepair for dataset

dataset ds = new dataset("exchange");

datatable dt = new datatable("foreignexchange");

ds.tables.add( dt );

dt.columns.add( "currency", typeof(string) );

dt.columns.add( "bankbuytt", typeof(double) );

dt.columns.add( "bankbuynotes", typeof(double) );

dt.columns.add( "banksell", typeof(double) );

dt.columns.add( "baseline", typeof(double) );

xmldatadocument xmldoc = new xmldatadocument( ds );

regex expr = new regex(

@"<tr bgcolor=#\w+ ><td height=20>(?<currency>.*)</td>\s*" +

@"<td height=20><p align=right>(?<bankbuytt>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<buynotes>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<sell>\d*.?\d*)(&nbsp)+.?</td>\s*" +

@"<td height=20><p align=right>(?<base>\d*.?\d*)(&nbsp)+.?</td>\s*"

, regexoptions.compiled);

for( match m = expr.match(webcontent) ; m.success ; m=m.nextmatch() )

{

string key;

datarow row = dt.newrow();

row["currency"] = m.groups["currency"];

key = m.groups["bankbuytt"].tostring();

row["bankbuytt"] = key.length > 0 ? convert.todouble( key )/100 : 0;

key = m.groups["buynotes"].tostring();

row["bankbuynotes"] = key.length > 0 ? convert.todouble( key )/100 : 0;

key = m.groups["sell"].tostring();

row["banksell"] = key.length > 0 ? convert.todouble( key )/100 : 0;

key = m.groups["base"].tostring();

row["baseline"] = key.length > 0 ? convert.todouble( key )/100 : 0;

dt.rows.add( row );

}

return xmldoc;

}

}

}

客户端也很容易,只要用wsdl生成了相应的webservice proxy后,直接调用就行了,由于我让server端返回了dataset,因此客户端直接用datagrid来显示dataset即可,非常easy,在这个问题上客户端没有什么技术关键点。

using system;

using system.threading;

using system.drawing;

using system.collections;

using system.componentmodel;

using system.windows.forms;

namespace bankdataclient

{

/// <summary>

/// summary description for frmmainbankrates.

/// </summary>

public class frmmainbankrates : system.windows.forms.form

{

private system.windows.forms.datagrid datagrid1;

private system.windows.forms.button btnconnect;

private system.data.dataset ds;

private bankdataclient.com.dancefires.[url]www.foreignexchange[/url] proxy = new bankdataclient.com.dancefires.www.foreignexchange();

private system.windows.forms.textbox txturl;

/// <summary>

/// required designer variable.

/// </summary>

private system.componentmodel.container components = null;

public frmmainbankrates()

{

//

// required for windows form designer support

//

initializecomponent();

try

{

txturl.text = system.configuration.configurationsettings.appsettings["url"];

proxy.url = txturl.text;

}

catch(exception)

{

proxy.url = "http://www.dancefires.com/chinabank/foreignexchange.asmx";

txturl.text = proxy.url;

}

}

/// <summary>

/// clean up any resources being used.

/// </summary>

protected override void dispose( bool disposing )

{

if( disposing )

{

if(components != null)

{

components.dispose();

}

}

base.dispose( disposing );

}

#region windows form designer generated code

/// <summary>

/// required method for designer support – do not modify

/// the contents of this method with the code editor.

/// </summary>

private void initializecomponent()

{

this.datagrid1 = new system.windows.forms.datagrid();

this.ds = new system.data.dataset();

this.btnconnect = new system.windows.forms.button();

this.txturl = new system.windows.forms.textbox();

((system.componentmodel.isupportinitialize)(this.datagrid1)).begininit();

((system.componentmodel.isupportinitialize)(this.ds)).begininit();

this.suspendlayout();

//

// datagrid1

//

this.datagrid1.datamember = "";

this.datagrid1.datasource = this.ds;

this.datagrid1.headerforecolor = system.drawing.systemcolors.controltext;

this.datagrid1.location = new system.drawing.point(32, 48);

this.datagrid1.name = "datagrid1";

this.datagrid1.size = new system.drawing.size(480, 256);

this.datagrid1.tabindex = 0;

//

// ds

//

this.ds.datasetname = "exchange";

this.ds.locale = new system.globalization.cultureinfo("zh-cn");

//

// btnconnect

//

this.btnconnect.location = new system.drawing.point(432, 16);

this.btnconnect.name = "btnconnect";

this.btnconnect.tabindex = 1;

this.btnconnect.text = "连接";

this.btnconnect.click += new system.eventhandler(this.btnconnect_click);

//

// txturl

//

this.txturl.location = new system.drawing.point(32, 16);

this.txturl.name = "txturl";

this.txturl.size = new system.drawing.size(384, 20);

this.txturl.tabindex = 2;

this.txturl.text = "";

//

// frmmainbankrates

//

this.autoscalebasesize = new system.drawing.size(5, 13);

this.clientsize = new system.drawing.size(544, 318);

this.controls.add(this.txturl);

this.controls.add(this.btnconnect);

this.controls.add(this.datagrid1);

this.name = "frmmainbankrates";

this.text = "foreign exchange rates of bank of china";

((system.componentmodel.isupportinitialize)(this.datagrid1)).endinit();

((system.componentmodel.isupportinitialize)(this.ds)).endinit();

this.resumelayout(false);

}

#endregion

private void btnconnect_click(object sender, system.eventargs e)

{

updatedatagrid();

}

private void updatedatagrid()

{

try

{

btnconnect.enabled = false;

txturl.readonly = true;

proxy.url = txturl.text;

ds = proxy.getforeignexchangeratesdataset();

datagrid1.setdatabinding( ds, "foreignexchange" );

datagrid1.update();

}

catch( exception err )

{

messagebox.show( err.message );

}

finally

{

txturl.readonly = false;

btnconnect.enabled = true;

}

}

[stathread]

static void main( string[] args )

{

application.run( new frmmainbankrates() );

}

}

}

有了这个例子,应该可以从中了解最基本的xml, webservice, regular expression, dataset, datagrid的知识。

软件所有代码,及相关截屏可以从下面的连接中获得:

http://www.dancefires.com/chinabank/

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 利用正则表达式将html网页数据变成Web Service-.NET教程,Web Service开发
分享到: 更多 (0)

相关推荐

  • 暂无文章