本文章讲叙了怎样在c#里处理xml文档,都是些比较基本的。
首先,我们先自建一个xml文档,如下:
<?xml version="1.0" encoding="UTF-8"?>
<peoplelist>
<person>
<name>Tom Stafford</name>
<title>CFO</title>
</person>
<person>
<name>Jane Goodwill</name>
<title>CEO</title>
</person>
<person>
<name>Tim Daly</name>
<title>CTO</title>
<title2>CTO0</title2>
</person>
<person>
<name>John Graver</name>
<title>CSO</title>
</person>
</peoplelist>
将其保存为:people.xml,:)
(1)查找XML文档里的指定节点
例如:要查找姓名为'Tim Daly'的用户的<title2>,则具体程序如下.
----
<%@page language="C#"%>
<%@import namespace="System.Xml"%>
<%@import namespace="System.Xml.Xsl"%>
<%@import namespace="System.Xml.XPath"%>
<script language="c#" runat="server">
void page_load(Object obj,EventArgs e)
{
string xmlfile="people.xml",xpath;
xpath=Server.MapPath(xmlfile);
XmlDocument myDoc = new XmlDocument(); //定义一个XmlDocument对象。
myDoc.Load(xpath);
message.Text=myDoc.SelectSingleNode ("//person[name='Tim Daly']").ChildNodes.Item(2).InnerText;}
</script>
<asp:label id="message" forecolor="red" runat="server"/>
解释:
其中//代表里面任意层的子节点。这样可以很快就找到所要的东西。
SelectSingleNode是找到一个单一的节点,SelectNodes可以找到许多节点
(2)用XML文档填充列表框,这里只用到<name>节点.
<%@ Page Language="C#" Debug="true" %>
<%@ Import Namespace="System.Collections" %>
<%@ Import Namespace="System.Xml" %>
<html>
<head>
<script language="C#" runat="server">
private void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList values = new ArrayList();//将其当作数据源
XmlDocument doc = new XmlDocument();//表示XML文档
doc.Load(Server.MapPath("people.xml"));
//返回一个XmlNodeList集合,包含与指定名称匹配的所有子代元素列表
XmlNodeList elemList = doc.GetElementsByTagName("name");//System.Xml 命名空间
for (int i=0; i < elemList.Count; i++)
{
values.Add (elemList[i].InnerXml);
}
ListBox1.DataSource = values;
ListBox1.DataBind();
}
}
//得到列表项,被选中项的文本
private void SubmitBtn_Click(Object sender, EventArgs e)
{
if(ListBox1.SelectedIndex>-1)
Label1.Text = "Selected Option: " + ListBox1.SelectedItem.Text + "<p>";
}
</script>
</head>
<body>
<form runat=server>
<h3>Data Binding ListBox</h3>
<asp:Label id="Label1" font-name="Verdana" font-size="10pt" runat="server"/>
<asp:ListBox id="ListBox1" SelectionMode="Single" Rows="1" runat="server"/>
<asp:button id="Button1" Text="Submit" onClick="SubmitBtn_Click" runat="server"/>
</form>
</body>
</html>
==============================================
(3)把XML文档通过DataSet读入到Repeater中.
你也可把它读入到DataSet.原理是一样的.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" %>
<html>
<head>
<title>读入到Repeater</title>
<script language="C#" runat=server>
public void Page_Load(Object obj,EventArgs e)
{
string xpath="db/people.xml" ;
try
{
DataSet ds= new DataSet();
FileStream fs= new FileStream(Server.MapPath(xpath),FileMode.Open,FileAccess.Read,FileShare.ReadWrite) ;
ds.ReadXml(new StreamReader(fs));
fs.Close();
Trace.Warn("表记录数",Convert.ToString(ds.Tables[0].Rows.Count));
MyDataList.DataSource=ds.Tables[0].DefaultView;
MyDataList.DataBind();
}
catch (Exception ed)
{
Response.Write("<font color=#FF0000>"+ed.ToString()+"</font>") ;
}
}
</script>
</head>
<body >
<ASP:Repeater id="MyDataList" runat="server">
<headertemplate>
<h5> Viewer Details </h5>
</headertemplate>
<itemtemplate>
<br>
<table class="mainheads" width="60%" style="font: 8pt verdana" >
<tr style="background-color:#FFFFCC">
<td>name:</td>
<td><%# DataBinder.Eval(Container.DataItem, "name") %></td>
</tr>
<tr style="background-color:#FFFFCC">
<td>title:</td>
<td><%# DataBinder.Eval(Container.DataItem, "title")%></td>
</tr>
<tr style="background-color:#FFFFCC">
<td>title2:</td>
<td><%# DataBinder.Eval(Container.DataItem, "title2") %></td>
</tr>
</table><br>
</itemtemplate>
</ASP:Repeater>
</body>
</html>
---------
(4)把Repeater中的数据保存到Xml中,同理,你也可用于DataSet.
,例子中增加了新的一行,并把编辑后的结果保存到XML
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Page Language="C#" Trace="true"%>
<html>
<head>
<title>Saurabh's XML Counter Script</title>
<script language="C#" runat=server>
public void Page_Load(Object obj,EventArgs e)
{
string dataFile="db/people.xml" ;
if(!Page.IsPostBack)
{
try {
DataSet ds= new DataSet();
FileStream fint;
fint= new FileStream(Server.MapPath(dataFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite) ;
ds.ReadXml(fint);
fint.Close();
if(Session["counter"]==null)
{
DataRow DR=ds.Tables[0].NewRow();
DR["name"]="myname";
DR["title"]="test";
DR["title2"]="test2";
ds.Tables[0].Rows.Add(DR);
FileStream fOut ;
fOut = new FileStream(Server.MapPath(dataFile), FileMode.Open, FileAccess.Write, FileShare.ReadWrite) ;
ds.WriteXml(fOut, XmlWriteMode.WriteSchema);
fOut.Close();
Session["counter"]="Set" ;
}
Trace.Warn("表记录数",ds.Tables[0].Rows.Count.ToString());
}
catch(Exception edd)
{
Response.Write("<font color=#FF0000>"+edd.ToString()+"</font>") ;
}
}
}
</script>
</body>
</html>
----------------------
(5)读取URL里面的XML数据
C#读取URL里面的XML数据问题,正常情况下,都是读取静态的XML文件,但是在证券领域里面,XML数据是随时更新的。
比如第三方想我们提供XML数据,我们给第二方作开发,而第三提供给我们的是一个URL,这个URL是XML格式的内容,包含着我们要得数据。
这里例子是读取CSDN上的URL.
using System;
using System.Xml;
namespace ConsoleApplication5
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.Load("http://www.csdn.net/expert/topic/1094/1094085.xml?temp=.9642145");
doc.Save(Console.Out );
}
}
}
这样,该C#程序就会把从远程ASP页面传过来的XML显示在Console.Out(控制台的输出)了.
---------------------------------------------------------------------------------------------------------------------------------------------------
外一:
123.xml文件内容:
<?xml version="1.0" encoding="gb2312"?>
<IMClientStart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Server>
<IP>192.168.0.1</IP>
<Port>8888</Port>
</Server>
<UserList>
<UserID>1004</UserID>
<UserID>1022</UserID>
<UserID>1001</UserID>
<UserID>1006</UserID>
<UserID>1023</UserID>
<UserID>1000</UserID>
<UserID>1014</UserID>
<UserID>1002</UserID>
<UserID>1013</UserID>
<UserID>1011</UserID>
<UserID>1010</UserID>
<UserID>1012</UserID>
<UserID>1018</UserID>
<UserID>1005</UserID>
<UserID>1032</UserID>
<UserID>1003</UserID>
<UserID>1007</UserID>
<UserID>1009</UserID>
<UserID>1008</UserID>
<UserID>1019</UserID>
<UserID>1021</UserID>
<UserID>1020</UserID>
<UserID>1024</UserID>
</UserList>
</IMClientStart>
读取函数:
string nodeText="",ip="",port="";
System.Xml.XmlTextReader reader = new XmlTextReader( "123.xml" );
reader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
while( reader.Read() )
{
if( reader.NodeType == System.Xml.XmlNodeType.Element )
{
nodeText = reader.Name;
switch( nodeText )
{
case "IP":
ip = reader.ReadString();
break;
case "Port":
port = reader.ReadString();
break;
case "UserID":
Login.UserIDList.Add( reader.ReadString());
break;
}
}
}
//赋值给textBox
this.textBox1.text = ip;