asp.net中没有必要一定用Xml
不过.net对xml的支持倒是很好
并且,整个.net架构中,配置文件都是以xml的方式保存的具体的
参考
ms-help://MS.VSCC/MS.MSDNVS.2052/cpguide/html/cpconemployingxmlinnetframework.htm
不过.net对xml的支持倒是很好
并且,整个.net架构中,配置文件都是以xml的方式保存的具体的
参考
ms-help://MS.VSCC/MS.MSDNVS.2052/cpguide/html/cpconemployingxmlinnetframework.htm
解决方案 »
- 在GridView的模板列里拖拉了一个FileUpload控件,可是我在程序里怎样访问这个控件呢?
- select top 后传参数的问题
- 怎样获取TreeView中的接点名称
- C:\Documents and Settings\wkm\VSWebCache\KF20\Do For Try\obj\Debug\CSC42.tmp”不是有效的 Win32 资源文件
- 询2003绘统计图控件
- showModalDialog的问题,GGJJMM都进来看看
- 关于使用Microsoft Internet Explorer WebControls的问题!
- 请问webform的关闭窗体方法和事件
- 求助:当SqlDataSource数据源空时gridview不能显示
- 请问框架集问题
- 如何在DataTable中的第一行处插入一条纪录!!
- 大家好,我接下来应该学,请帮帮我!
<books>
<book>
<isbn>0070653623</isbn>
<author>Jack Trout, Steve Rivkin</author>
<title>The Power of Simplicity</title>
<category>selfhelp</category>
<comments>A Real Fun Read</comments>
</book>
<book>
<isbn>0887306667</isbn>
<author>Al Reiss, Jack Trout</author>
<title>22 Immutable Laws of Marketing</title>
<category>eting</category>
<comments>This team offers more profound advice about creating world class eting campaigns that will be viable for a hundred years.</comments>
</book> <book>
<isbn>0887309372</isbn>
<author>Al Reiss, Laura Reiss</author>
<title>22 Immutable Laws of Branding</title>
<category>eting</category>
<comments>This book is great for people who used 22 Immutable Laws of Marketing to build a brand and now want to strengthen that brand.</comments>
</book>
<book>
<isbn>0679757651</isbn>
<author>Tom Peters</author>
<title>Circle of Innovation</title>
<category>eting</category>
<comments>His most recent book is his best by far!</comments>
</book>
<book>
<isbn>0884270610</isbn>
<author>Eli Goldthrait</author>
<title>The Goal</title>
<category>management</category>
<comments>Advocate of Theory of Constraints as applied to managment and optimization.</comments>
</book> <book>
<isbn>068485600X</isbn>
<author>Jeff Cox, Howard Stevens</author>
<title>Selling the Wheel</title>
<category>management</category>
<comments>Excellent Treatise/Novel on the entire Sales Cycle</comments>
</book> <book>
<isbn>0672316498</isbn>
<author>Alan Cooper</author>
<title>The Inmates Are Running The Asylum</title>
<category>management</category>
<comments>The father of Visual Basic and creator of the new art of Interaction Design - very valuable in designing websites. Basically the worlds most cutting edge thinker in User Interface design aimed at simplifying software use.</comments>
</book>
</books> --------
books.xml文件结束.continue......
---------------------------------
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %><HTML>
<script language="VB" runat="server">
' 02/14/02 -Enhancements to original version by Paul Chu
' 1. add code to support sorting
' 2. add code to support actual Updating and Deleting of XML data
' 3. add code to use javascript to confirm delete
' 4. insert a blank top at the top of datagrid - add code to add a new row
' 5. Modify update and delete eventhandlers to update XML file using dataset
' Blank Row in Datagrid Concept
' A datagrid is bound to a datasource e.g.datatables which
' has rows of data to disply.
' If we add a new row of data to the datatable then it will
' also show in the datagrid.
' This basic concept enables us to use the datagrid to update a new row
' and the current eventhandler code will handle the "insert"
' just like an update of an existing datarow in the dataset.
' The trick is that the new row in the dataset is all we need
' to update to fool the datagrid.' ========================================dim gXmlfile as string = "books.xml" ' <============ your file
dim gXmlPath as string' =================================Sub Page_Load(Src As Object, E As EventArgs) gxmlpath = server.mappath( gXmlfile ) 'file is in same folder as page
If Not (IsPostBack)
DataLoad("isbn") '-- sort by ISBN
End If
End Sub ' ========================================Sub DataLoad(parmsort as string)
Dim ds As New DataSet
Dim FS As New FileStream(Server.MapPath(gXmlFile), FileMode.Open)
ds.ReadXml(FS)' 02/14/02 pchu handle an empty file ---------------------------
if ds.tables.count = 0 then
ds.tables.add( MakeBooksTable() )
end if
trace.warn ( "rowcount1 = " , cstr(ds.Tables(0).rows.count )) ' 02/14/02 pchu ---------------------------
' Add code to sort the dataview if parmsort is present'ok let's get fancy and insert a blank row at the top
dim sw1 as integer = 1
select case sw1
case 1
dim dr as datarow = ds.Tables(0).newrow()
'put something in the first column ISBN
dr("ISBN") = " Add ISBN"
ds.Tables(0).rows.insertat(dr, 0)
trace.warn ( "rowcount2 = " , cstr(ds.Tables(0).rows.count ))
end select
'create dv and bind it to datagrid
dim dv as dataview
dv = new DataView(ds.Tables(0))
if parmsort.length > 0 then
dv.sort = parmsort
end if MyDataGrid.DataSource = dv
'old MyDataGrid.DataSource = new DataView(ds.Tables(0))
' 02/14/02 pchu --------------------------- MyDataGrid.DataBind()
FS.close()
END SUB ' ========================================Sub DataSort(Src As Object, E As DataGridSortCommandEventArgs)
' Bug if we sort, then Edit Item Becomes Wrong
IF MyDataGrid.EditItemIndex=-1 THEN
DataLoad(e.sortexpression)
ELSE
response.write ("Can't sort until editing is done!")
END IF
End Sub ' ========================================Sub DataDelete(Sender As Object, E As DataGridCommandEventArgs)
DIM deletekey as string
IF MyDataGrid.EditItemIndex=-1 THEN
deletekey=MyDataGrid.DataKeys(CInt(E.Item.ItemIndex))
response.write ("Delete completed for key = " & deletekey)
ELSE
response.write ("Can't delete until editing is done!")
END IF
'' Dim currentRow As Integer = e.Item.DataSetIndex
'ok too!
Dim currentRow As Integer = e.Item.itemindex'02/16/02 BugFix: because the datagrid has an insert row which is NOT in the
' in the dataset table, we have to subtract one to compensate for the that fact
currentrow = currentrow - 1 'bug fix: subtract 1 because the grid has a insert row
trace.warn (" current row to delete ", cstr(currentrow) )
' reload the XML file into a dataset
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath(gXmlFile)) ' get a reference to this row of data
Dim row As DataRow = ds.Tables(0).Rows( currentrow ) row.delete() '-- kill this row in the dataset
' save the updated dataset to the XML file
ds.WriteXml(Server.MapPath(gXmlFile)) mydatagrid.EditItemIndex = -1 'exit delete mode dataload("") ' redisplay and rebind datagrid
END SUB ' ========================================Sub DataEdit(Sender As Object, E As DataGridCommandEventArgs)
DIM editkey as string
trace.warn ("e.item.itemindex = ", cstr(e.item.itemindex) )
MyDataGrid.EditItemIndex = Cint(E.Item.ItemIndex )
editkey=MyDataGrid.DataKeys(CInt(E.Item.ItemIndex)) trace.warn ("page.aspx", "To Be Edited" & editkey) SetEditMode( "on" ) DataLoad("")
End Sub ' ========================================Sub DataCancel(Sender As Object, E As DataGridCommandEventArgs)
MyDataGrid.EditItemIndex = -1
trace.warn ("page.aspx", "edit was cancelled") SetEditMode( "off" )
DataLoad("")
End Sub '====================================================Public Sub DataUpdate(ByVal source As Object, ByVal e _
As System.Web.UI.WebControls.DataGridCommandEventArgs) 'This eventhandler will process both an Update and a Add because in both
' cases the dataset has an existing row to "update", because we added a
' dummy row to the dataset table for the add Dim cols As String() = {"isbn", "author", "title", "category", "comments"} Dim numCols As Integer = e.Item.Cells.Count
Dim currentRow As Integer = e.Item.DataSetIndex
' reload the XML file into a dataset
Dim ds As New DataSet()
ds.ReadXml(Server.MapPath(gXmlFile))
dim row as datarow
trace.warn("update row = ", currentrow.tostring() )
trace.warn("datasetindex row = ", e.Item.DataSetIndex.tostring() )
' 02/14/02 pchu handle an empty file ---------------------------
if ds.tables.count = 0 then
ds.tables.add( MakeBooksTable() )
end if
if currentrow = 0 then
row = ds.tables(0).newrow()
else
Row = ds.Tables(0).Rows(e.Item.DataSetIndex - 1) 'need to sub 1 because we have an inserted row
end if ' get a reference to this row of data
'' Dim row As DataRow = ds.Tables(0).Rows(e.Item.DataSetIndex) ' get the values and update the datarow
Dim I, J As Integer
j = -1
Trace.Warn("aspx.page", "numcols = " & CStr(numCols))
For I = 2 To numCols - 1 'skip first and 2nd columns (Edit/Delete command column)
j += 1
Dim currentTextBox As TextBox
currentTextBox = CType(e.Item.Cells(I).Controls(0), TextBox )
row(cols(j)) = currentTextBox.Text
Trace.Warn(I.ToString(), CStr(cols(j)) & " = " & currentTextBox.Text)
Nextif currentrow = 0 then
ds.tables(0).rows.insertat(row, 0 )
end if ' save the updated data as the XML file
ds.WriteXml(Server.MapPath(gXmlFile)) mydatagrid.EditItemIndex = -1 SetEditMode( "off" ) dataload("")
End Sub' ===================================
public sub dg_itemcreated ( sender as object, e as datagriditemeventargs )'-- add logic to modify EDIT and Suppress the Delete
if e.item.itemindex = 0 then 'first row
'reference the delete button
'???????????????????? can we use FindControl here to locate controls
dim lbDelete as linkbutton = e.item.cells(0).controls(0)
dim lbEdit as linkbutton = e.item.cells(1).controls(0)trace.warn ("page.aspx", "lbDelete = " & lbDelete.text )
trace.warn ("page.aspx", "lbEdit = " & lbEdit.text )
if lbDelete.text = "Delete Book" then
lbDelete.text = ""
end if
if lbEdit.text = "Edit" then
lbEdit.text = "AddNew"
end if
if lbEdit.text = "Update" then
lbEdit.text = "Insert"
end if
end ifif e.item.itemindex > 0 then 'first row select case e.item.itemtype
case listitemtype.item
dim mydeletebutton as tablecell
mydeletebutton = e.item.cells(0)
mydeletebutton.attributes.add("onclick", _
"return confirm('Are you sure you want to Delete ?');" )
case listitemtype.alternatingitem
dim mydeletebutton as tablecell
mydeletebutton = e.item.cells(0)
mydeletebutton.attributes.add("onclick", _
"return confirm('Are you sure you want to Delete ?');" )
end select
end if
end sub' =========================sub SetEditMode ( state as string)
select case state
case "on"
MyDataGrid.columns(0).visible = False 'Hide Delete Column
case else
MyDataGrid.columns(0).visible = True 'Show Delete Columnend select
end sub' ========================================Private Function MakeBooksTable() As DataTable
'' theColumn.DefaultValue = "Fname"
' Dim fNameColumn As DataColumn = New DataColumn()
'' idColumn.AutoIncrement = True ' Create a new DataTable titled 'Books.'
Dim theTable As DataTable = new DataTable("Books")
' Add three column objects to the table.
Dim theColumn1 As DataColumn = new DataColumn()
theColumn1.DataType = System.Type.GetType("System.String")
theColumn1.ColumnName = "isbn"
theTable.Columns.Add(theColumn1) Dim theColumn2 As DataColumn = new DataColumn()
theColumn2.DataType = System.Type.GetType("System.String")
theColumn2.ColumnName = "author"
theTable.Columns.Add(theColumn2) Dim theColumn3 As DataColumn = new DataColumn()
theColumn3.DataType = System.Type.GetType("System.String")
theColumn3.ColumnName = "title"
theTable.Columns.Add(theColumn3) Dim theColumn4 As DataColumn = new DataColumn()
theColumn4.DataType = System.Type.GetType("System.String")
theColumn4.ColumnName = "category"
theTable.Columns.Add(theColumn4) Dim theColumn5 As DataColumn = new DataColumn()
theColumn5.DataType = System.Type.GetType("System.String")
theColumn5.ColumnName = "comments"
theTable.Columns.Add(theColumn5) ' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = theColumn1
theTable.PrimaryKey = keys
' Return the new DataTable.
MakeBooksTable = theTable
End Function' ========================================
</script>
<!-- =================================================== -->
<body>
<h3><font face="Verdana">The Best Books Ever: Enhanced Version 2 by Paul Chu</font>
<span runat="server" id="MySpan"></h3>
<h2>Updateable Datagrid with Blank Row update file: <% = gxmlfile %></h2> <form runat="server">
<P>
<ASP:DataGrid id="MyDataGrid" runat="server"
AllowSorting="True"
OnSortCommand="DataSort"
OnDeleteCommand="DataDelete"
OnEditCommand="DataEdit"
OnCancelCommand="DataCancel"
OnUpdateCommand="DataUpdate"
DataKeyField="isbn"
Width="100%"
BackColor="White"
BorderColor="Black"
CellPadding=3
Font-Name="Verdana"
Font-Size="8pt"
Headerstyle-BackColor="lightblue"
Headerstyle-Font-Size="10pt"
Headerstyle-Font-Style="bold"
MaintainState="true"
Font-Names="Verdana"
onitemcreated="dg_itemcreated"
>
<HeaderStyle Font-Size="10pt" BackColor="LightBlue">
</HeaderStyle>
<Columns>
<asp:ButtonColumn Text="Delete Book" CommandName="Delete"></asp:ButtonColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit">
<ItemStyle Wrap="False">
</ItemStyle>
</asp:EditCommandColumn>
</Columns>
</ASP:DataGrid></P></form></SPAN>
</body>
</HTML>
--------------------------
EditXmlWithDataGrid.aspx 文件结束 continue......
ASPX Source:EditXmlWithDataGrid.aspx
XML Document:books.xml
--------------------------------------
EditXmlWithDataGrid.src 结束。将这三个文件放在同一个虚拟目录下。试试。
namespace HowTo.Samples.XML
{using System;
using System.IO;
using System.Xml;public class ReadXmlFileSample
{
private const string document = "books.xml"; public static void Main()
{
ReadXmlFileSample myReadXmlFileSample = new ReadXmlFileSample();
myReadXmlFileSample.Run(document);
} public void Run(String args)
{
XmlTextReader reader = null; try
{
// 用 XmlTextReader 加载文件
Console.WriteLine ("正在读取文件 {0} ...", args);
reader = new XmlTextReader (args);
Console.WriteLine ("已成功读取文件 {0} ...", args); // 处理所提供的 XML 文件
Console.WriteLine ("正在处理 ...");
Console.WriteLine ();
FormatXml(reader, args);
}
catch (Exception e)
{
Console.WriteLine ("未能读取文件 {0}", args);
Console.WriteLine ("异常:{0}", e.ToString());
} finally
{
Console.WriteLine();
Console.WriteLine("对文件 {0} 的处理已完成。", args);
// 通过 XmlTextReader 完成
if (reader != null)
reader.Close();
}
} private static void FormatXml (XmlReader reader, String filename)
{
int declarationCount=0, piCount=0, docCount=0, commentCount=0, elementCount=0, attributeCount=0, textCount=0, whitespaceCount=0; while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.XmlDeclaration:
Format (reader, "XmlDeclaration");
declarationCount++;
break;
case XmlNodeType.ProcessingInstruction:
Format (reader, "ProcessingInstruction");
piCount++;
break;
case XmlNodeType.DocumentType:
Format (reader, "DocumentType");
docCount++;
break;
case XmlNodeType.Comment:
Format (reader, "Comment");
commentCount++;
break;
case XmlNodeType.Element:
Format (reader, "Element");
elementCount++;
if (reader.HasAttributes)
attributeCount += reader.AttributeCount;
break;
case XmlNodeType.Text:
Format (reader, "Text");
textCount++;
break;
case XmlNodeType.Whitespace:
whitespaceCount++;
break;
}
} // 显示该文件的统计信息。
Console.WriteLine ();
Console.WriteLine("{0} 文件的统计信息", filename);
Console.WriteLine ();
Console.WriteLine("Xml 声明:{0}",declarationCount++);
Console.WriteLine("处理指令:{0}",piCount++);
Console.WriteLine("文档类型:{0}",docCount++);
Console.WriteLine("注释:{0}",commentCount++);
Console.WriteLine("元素:{0}",elementCount++);
Console.WriteLine("属性:{0}",attributeCount++);
Console.WriteLine("文本:{0}",textCount++);
Console.WriteLine("空白:{0}",whitespaceCount++);
} private static void Format(XmlReader reader, String nodeType)
{
// 格式化输出
Console.Write(reader.Depth + " ");
Console.Write(reader.AttributeCount + " ");
for (int i=0; i < reader.Depth; i++)
{
Console.Write('\t');
} Console.Write(reader.Prefix + nodeType + "<" + reader.Name + ">" + reader.Value); // 显示当前节点的属性值
if (reader.HasAttributes)
{
Console.Write(" 属性:"); for (int j=0; j < reader.AttributeCount; j++)
{
Console.Write(" [{0}] " + reader[j], j);
}
}
Console.WriteLine();
}} // 结束类 ReadXmlFileSample
} // 结束命名空间 HowTo.Samples.XML
using System;
using System.IO;
using System.Xml;namespace HowTo.Samples.XML
{public class MultipleXmlReaderSample
{
private const String document = "twopart.xml"; public static void Main()
{
MultipleXmlReaderSample myMultipleXmlReaderSample = new MultipleXmlReaderSample();
myMultipleXmlReaderSample.Run(document);
} public void Run(String args)
{
try
{
//为指定的源文件创建新文件流。
FileStream filestreamSource = new FileStream(args, FileMode.Open, FileAccess.Read);
//用该文件流创建新读取器
XmlTextReader reader = new XmlTextReader(filestreamSource);
//读取 XML 文档的第一部分
while(reader.Read())
{
//显示元素并在 part1 结束元素标记处停止读取
//然后转到 ReadPart2 启动另一个读取器,读取文件的其余部分。
switch(reader.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine("名称:{0}", reader.Name);
Console.WriteLine(" 前缀:{0}", reader.Prefix);
Console.WriteLine(" 本地名称:{0}", reader.LocalName);
Console.WriteLine(" 命名空间:{0}", reader.NamespaceURI);
break;
case XmlNodeType.EndElement:
//用本地名称等于 part1 来停止在元素的结束元素处的读取
if ("part1"==reader.LocalName)
{
Console.WriteLine("终止读取第 1 部分...");
Console.WriteLine();
goto ReadPart2;
}
break;
}
} //读取 XML 文档的其余部分
ReadPart2:
Console.WriteLine("开始读取第 2 部分...");
//创建 XmlNamespaceManager 并为文档添加命名空间。
XmlNamespaceManager nsmanager = new XmlNamespaceManager(reader.NameTable);
//设置默认命名空间,第一个参数为空。
nsmanager.AddNamespace(String.Empty, "http://tempuri.org/mydefaultnamespace");
nsmanager.AddNamespace("myns", "http://tempuri.org/mynamespace");
nsmanager.AddNamespace("yourns", "http://tempuri.org/yournamespace");
XmlParserContext pc = new XmlParserContext(reader.NameTable, nsmanager, reader.XmlLang, XmlSpace.Default); // 将文件流重置到源流的开始处
filestreamSource.Seek(0, SeekOrigin.Begin);
XmlTextReader reader2 = new XmlTextReader(filestreamSource, XmlNodeType.Element, pc); while(reader2.Read())
{
switch (reader2.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine("元素名称:{0}", reader2.Name);
Console.WriteLine(" 前缀:{0}", reader2.Prefix);
Console.WriteLine(" 本地名称:{0}", reader2.LocalName);
Console.WriteLine(" 命名空间:{0}", reader2.NamespaceURI);
break;
case XmlNodeType.EndElement:
//用本地名称等于 part2 来停止在元素的结束元素处的读取
if ("part2"==reader2.LocalName)
{
Console.WriteLine("终止读取第 2 部分...");
goto Done;
}
break;
}
} Done:
Console.WriteLine("完成。");
reader.Close(); }
catch (Exception e)
{
Console.WriteLine ("异常:{0}", e.ToString());
}
}
} // 结束类 MultipleXmlReaderSample
} // 结束命名空间 HowTo.Samples.XML
namespace HowTo.Samples.XML
{using System;
using System.IO;
using System.Xml;public class SaveXmlDocumentSample
{
private const String document = "books.xml";
private const String updatedDocument = "updatebooks.xml"; public static void Main()
{
String[] args = {document, updatedDocument};
SaveXmlDocumentSample mySaveXmlDocumentSample = new SaveXmlDocumentSample();
mySaveXmlDocumentSample.Run(args);
} public void Run(String[] args)
{
try
{
// 创建 XmlDocument 并从文件加载 XML
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load (new XmlTextReader (args[0]));
Console.WriteLine ("已成功与 XML 数据一起加载 XmlDocument ...");
Console.WriteLine(); IncreasePrice(myXmlDocument.DocumentElement); // 以 XML 形式写出数据
myXmlDocument.Save(args[1]);
Console.WriteLine();
Console.WriteLine("更新后的价格保存在文件 {0} 中", args[1]);
}
catch (Exception e)
{
Console.WriteLine ("异常:{0}", e.ToString());
}
} public void IncreasePrice(XmlNode node)
{
if (node.Name == "price")
{
node = node.FirstChild;
Decimal price = Decimal.Parse(node.Value);
// 将所有书价提高 2%
String newprice = ((Decimal)price*(new Decimal(1.02))).ToString("#.00");
Console.WriteLine("原价格 = " + node.Value + "\t新价格 = " + newprice);
node.Value = newprice;
} node = node.FirstChild;
while (node != null)
{
IncreasePrice(node);
node = node.NextSibling;
}
}} // 结束列 SaveXmlDocumentSample
} // 结束命名空间 HowTo.Samples.XML