-
如何读写XML文件
2006-12-01 17:55:00using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;... this.saveFileDialog1.Filter = "所有XML文件|...using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;namespace MyDB
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Splitter splitter1;
private System.Data.OleDb.OleDbConnection oleDbConnection1;
private System.Data.OleDb.OleDbCommand oleDbSelectCommand1;
private System.Data.OleDb.OleDbCommand oleDbInsertCommand1;
private System.Data.OleDb.OleDbCommand oleDbUpdateCommand1;
private System.Data.OleDb.OleDbCommand oleDbDeleteCommand1;
private System.Data.OleDb.OleDbDataAdapter oleDbDataAdapter1;
private System.Data.DataSet dataSet1;
private System.Windows.Forms.DataGrid dataGrid1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.RichTextBox richTextBox1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.splitter1 = new System.Windows.Forms.Splitter();
this.oleDbConnection1 = new System.Data.OleDb.OleDbConnection();
this.oleDbSelectCommand1 = new System.Data.OleDb.OleDbCommand();
this.oleDbInsertCommand1 = new System.Data.OleDb.OleDbCommand();
this.oleDbUpdateCommand1 = new System.Data.OleDb.OleDbCommand();
this.oleDbDeleteCommand1 = new System.Data.OleDb.OleDbCommand();
this.oleDbDataAdapter1 = new System.Data.OleDb.OleDbDataAdapter();
this.dataSet1 = new System.Data.DataSet();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.button4);
this.panel1.Controls.Add(this.button3);
this.panel1.Controls.Add(this.button2);
this.panel1.Controls.Add(this.textBox1);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.comboBox1);
this.panel1.Controls.Add(this.label1);
this.panel1.Controls.Add(this.button1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(400, 56);
this.panel1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(288, 8);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(104, 21);
this.textBox1.TabIndex = 4;
this.textBox1.Text = "";
//
// label2
//
this.label2.Location = new System.Drawing.Point(208, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 16);
this.label2.TabIndex = 3;
this.label2.Text = "设置查询值:";
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.Items.AddRange(new object[] {
"客户ID",
"公司名称",
"联系人姓名",
"联系人头衔",
"地址",
"城市",
"地区",
"邮政编码",
"国家",
"电话",
"传真",
"所有记录"});
this.comboBox1.Location = new System.Drawing.Point(96, 8);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(104, 20);
this.comboBox1.TabIndex = 2;
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 16);
this.label1.TabIndex = 1;
this.label1.Text = "选择查询条件:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 32);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 23);
this.button1.TabIndex = 0;
this.button1.Text = "开始查询";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter1.Location = new System.Drawing.Point(0, 56);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(400, 3);
this.splitter1.TabIndex = 1;
this.splitter1.TabStop = false;
//
// oleDbConnection1
//
this.oleDbConnection1.ConnectionString = @"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=""Northwind.mdb"";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False";
//
// oleDbSelectCommand1
//
this.oleDbSelectCommand1.CommandText = "SELECT * FROM 客户 ";
this.oleDbSelectCommand1.Connection = this.oleDbConnection1;
//
// oleDbDataAdapter1
//
this.oleDbDataAdapter1.DeleteCommand = this.oleDbDeleteCommand1;
this.oleDbDataAdapter1.InsertCommand = this.oleDbInsertCommand1;
this.oleDbDataAdapter1.SelectCommand = this.oleDbSelectCommand1;
this.oleDbDataAdapter1.UpdateCommand = this.oleDbUpdateCommand1;
//
// dataSet1
//
this.dataSet1.DataSetName = "NewDataSet";
this.dataSet1.Locale = new System.Globalization.CultureInfo("zh-CN");
//
// dataGrid1
//
this.dataGrid1.CaptionVisible = false;
this.dataGrid1.DataMember = "";
this.dataGrid1.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(0, 59);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(400, 243);
this.dataGrid1.TabIndex = 2;
//
// button2
//
this.button2.Location = new System.Drawing.Point(104, 32);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 23);
this.button2.TabIndex = 5;
this.button2.Text = "写入XML文件";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(200, 32);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(96, 23);
this.button3.TabIndex = 6;
this.button3.Text = "读取XML文件";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(296, 32);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(96, 23);
this.button4.TabIndex = 7;
this.button4.Text = "显示XML文件";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// openFileDialog1
//
this.openFileDialog1.Filter = "所有XML文件|*.XML";
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "所有XML文件|*.XML";
//
// richTextBox1
//
this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.richTextBox1.Location = new System.Drawing.Point(0, 59);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(400, 243);
this.richTextBox1.TabIndex = 3;
this.richTextBox1.Text = "";
this.richTextBox1.Visible = false;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(400, 302);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.splitter1);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "演示读写XML文件";
this.Load += new System.EventHandler(this.Form1_Load);
this.Closed += new System.EventHandler(this.Form1_Closed);
this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);}
#endregion/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}private void Form1_Load(object sender, System.EventArgs e)
{//显示所有记录
this.oleDbDataAdapter1.Fill(this.dataSet1,"客户");
this.dataGrid1.DataSource=this.dataSet1;
if(!this.dataGrid1.IsExpanded(0))
this.dataGrid1.Expand(0);
}private void button1_Click(object sender, System.EventArgs e)
{//查询记录
try
{
this.dataSet1.Clear();
string StrSQL="SELECT * FROM 客户 WHERE ";
StrSQL+=this.comboBox1.Text+" LIKE '";
StrSQL+=this.textBox1.Text+"'";
if(this.comboBox1.Text=="所有记录")
StrSQL="SELECT * FROM 客户";
this.oleDbDataAdapter1.SelectCommand.CommandText=StrSQL;
this.oleDbDataAdapter1.SelectCommand.Connection=this.oleDbConnection1;
//打开数据库连接
this.oleDbConnection1.Open();
//执行SQL命令
this.oleDbDataAdapter1.SelectCommand.ExecuteNonQuery();
//关闭连接
this.oleDbConnection1.Close();
//更新数据集
this.oleDbDataAdapter1.Fill(this.dataSet1,"客户");
this.dataGrid1.DataSource=this.dataSet1;
this.richTextBox1.Visible=false;
this.dataGrid1.Visible=true;
}
catch(Exception Err)
{
MessageBox.Show("查询数据集记录操作失败:"+Err.Message,"信息提示",
MessageBoxButtons.OK,MessageBoxIcon.Information);
//如果打开了连接,则关闭它
if(this.oleDbConnection1.State==ConnectionState.Open)
{
this.oleDbConnection1.Close();
}
}
}private void Form1_Closed(object sender, System.EventArgs e)
{//关闭程序
//如果打开了连接,则关闭它
if(this.oleDbConnection1.State==ConnectionState.Open)
{
this.oleDbConnection1.Close();
}
}private void button2_Click(object sender, System.EventArgs e)
{//写入XML文件
try
{
if(this.dataSet1==null)
return;
if(this.saveFileDialog1.ShowDialog()==DialogResult.Cancel)
return;
string FileName=this.saveFileDialog1.FileName;
if(FileName.Length<1)
return;
//将数据写入XML文件
this.dataSet1.WriteXml(FileName,XmlWriteMode.WriteSchema);
MessageBox.Show("写入XML文件操作成功!","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
catch(Exception Err)
{
MessageBox.Show("写入XML文件发生错误:"+Err.Message,"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
}private void button3_Click(object sender, System.EventArgs e)
{//读取XML文件
if(this.openFileDialog1.ShowDialog()==DialogResult.Cancel)
return;
string FileName=this.openFileDialog1.FileName;
if(FileName.Length<1)
return;
System.Xml.XmlTextReader MyReader=new System.Xml.XmlTextReader(FileName);
//从XmlTextReader中读取数据
this.dataSet1.ReadXml(MyReader,XmlReadMode.ReadSchema);
this.dataGrid1.DataSource=this.dataSet1;
this.richTextBox1.Visible=false;
this.dataGrid1.Visible=true;
}
private void button4_Click(object sender, System.EventArgs e)
{//显示XML文件
if(this.dataSet1==null)
return;
//取得XSD架构数据
this.richTextBox1.Text=this.dataSet1.GetXmlSchema();
//取得数据
this.richTextBox1.Text+=this.dataSet1.GetXml();
this.richTextBox1.Visible=true;
this.dataGrid1.Visible=false;
}
}
}
-
C#如何读写xml文件
2015-02-02 14:05:47C#如何读写xml文件 XML是一项热门的技术。它之所以能够引起人们的兴趣,一个主要的原因在于它十分的简单,人们可以很容易地理解和使用它。每一个程序员都能轻易地看懂一个XML文件,理解它包含的内容。 .NET中...C#如何读写xml文件
XML是一项热门的技术。它之所以能够引起人们的兴趣,一个主要的原因在于它十分的简单,人们可以很容易地理解和使用它。每一个程序员都能轻易地看懂一个XML文件,理解它包含的内容。.NET中包含了很多支持XML的类,这些类使得程序员使用XML编程就如同理解XML文件一样简单。在这篇文章中,我将给出这样的一个类的使用示例,这个类就是XmlTextWriter类。
XmlTextWriter类允许你将XML写到一个文件中去。这个类包含了很多方法和属性,使用这些属性和方法可以使你更容易地处理XML。为了使用这个类,你必须首先创建一个新的XmlTextWriter对象,然后你可以将XML片断加入到这个对象中。这个类中包含了不少的方法用于将各种类型的XML元素添加到XML文件中,下表给出了这些方法的名字和描述情况:
方法
描述WriteStartDocument
书写版本为“1.0”的 XML 声明WriteEndDocument
关闭任何打开的元素或属性Close
关闭流WriteDocType
写出具有指定名称和可选属性的 DOCTYPE 声明WriteStartElement
写出指定的开始标记WriteEndElement
关闭一个元素WriteFullEndElement
关闭一个元素,并且总是写入完整的结束标记WriteElementString
写出包含字符串值的元素WriteStartAttribute
书写属性的起始内容WriteEndAttribute
关闭上一个 WriteStartAttribute 调用WriteRaw
手动书写原始标记WriteString
书写一个字符串WriteAttributeString
出具有指定值的属性WriteCData
写出包含指定文本的 <![CDATA[...]]> 块WriteComment
写出包含指定文本的注释 <!--...-->WriteWhiteSpace
写出给定的空白WriteProcessingInstruction
写出在名称和文本之间带有空格的处理指令,如下所示:<?name text?>如果你对于XML十分熟悉,那么你一定能很好的理解上面的这些方法。下面我们将给出一个例子,在这个例子中,我们将先创建一个文档,添加一些元素,然后关闭这个文档。添加了元素后你还可以添加子元素,属性和其他内容。下面的代码就是这样的一个例子,它创建了一个文件名为title的XML文件。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlTextWriter writer = new XmlTextWriter("titles.xml", null);
//写入根元素
writer.WriteStartElement("items");
//加入子元素
writer.WriteElementString("title", "Unreal Tournament 2003");
writer.WriteElementString("title", "C&C: Renegade");
writer.WriteElementString("title", "Dr. Seuss's ABC");
//关闭根元素,并书写结束标签
writer.WriteEndElement();
//将XML写入文件并且关闭XmlTextWriter
writer.Close();
}
}
如果你编译并且执行上面的代码,你将创建这个XML文件,文件中包含如下内容:
<items>
<title>Unreal Tournament 2003</title>
<title>C&C: Renegade</title>
<title>Dr. Seuss's ABC</title>
</items>上面的代码创建了一个名为writer的XmlTextWriter对象。当这个对象被创建时,它被关联到一个名为titles.xml的文件。接着,程序创建了一个叫做items的根属性,WriteStartElement方法创建了这个属性的开始标签。接下来,程序调用了WriteElementString方法创建了三个子元素。从上面的代码你还可以看到,这个方法使用第一个参数(在上面的程序中是title)作为元素的标签;使用第二个参数作为元素的值。当你添加了所有的元素后,你需要关闭根元素。这时你可以调用WriteEndElement方法关闭那个最近被打开的元素;在本例中,这个最近被打开的元素就是根元素。当所有的数据都已经写好,根元素也已经关闭时,你可以将信息传送给你的XmlTextWriter。这意味着这时候你可以调用Close方法关闭它了。
上面的代码相对十分的简单,下面我们看一个使用了XmlTextWriter类中更多方法,功能更加完善的例子。
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlTextWriter writer = new XmlTextWriter("myMedia.xml", null);
//使用自动缩进便于阅读
writer.Formatting = Formatting.Indented;
//书写根元素
writer.WriteStartElement("items");
//开始一个元素
writer.WriteStartElement("item");
//向先前创建的元素中添加一个属性
writer.WriteAttributeString("rating", "R");
//添加子元素
writer.WriteElementString("title", "The Matrix");
writer.WriteElementString("format", "DVD");
//关闭item元素
writer.WriteEndElement(); // 关闭元素
//在节点间添加一些空格
writer.WriteWhitespace("\n");
//使用原始字符串书写第二个元素
writer.WriteRaw("<item>" +
"<title>BloodWake</title>" +
"<format>XBox</format>" +
"</item>");
//使用格式化的字符串书写第三个元素
writer.WriteRaw("\n <item>\n" +
" <title>Unreal Tournament 2003</title>\n" +
" <format>CD</format>\n" +
" </item>\n");
// 关闭根元素
writer.WriteFullEndElement();
//将XML写入文件并关闭writer
writer.Close();
}
}
上面代码编译运行后将得到myMedia.xml文件,文件的内容为: <items>
<item rating="R">
<title>The Matrix</title>
<format>DVD</format>
</item>
<item>
<title>BloodWake</title>
<format>XBox</format>
</item>
<item>
<title>Unreal Tournament 2003</title>
<format>CD</format>
</item>
</items>
上面代码中的注释说明了这个程序的功能是如何实现的。需要记住的一件事是:当调用方法开始一个操作时,你需要在程序的合适的地方调用方法结束这个操作。例如,你调用了StartElement,你就必须调用EndElement关闭元素;当然在这两个调用之间你也可以加入一个子元素。无论你何时调用EndElement方法,它总是关闭最近使用StartElement方法打开的那个元素(这和栈的工作方式很相似)。使用XmlTextWriter十分的容易,不过我还是建议你自己动手试试这些代码和方法。你试过以后会发现这些代码能够很容易地集成到你的程序中。你还应该记住,XmlTextWriter仅仅是.NET提供的众多XML类中的一个。和XmlTextWriter一样,其他的XML类也十分的容易使用
2)
我用的是一种很笨的方法,但可以帮助初学者了解访问XML节点的过程。已知有一个XML文件(bookstore.xml)如下:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
</bookstore>1、往<bookstore>节点中插入一个<book>节点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load("bookstore.xml");
XmlNode root=xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
XmlElement xe1=xmlDoc.CreateElement("book");//创建一个<book>节点
xe1.SetAttribute("genre","李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//设置该节点ISBN属性XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="CS从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//添加到<book>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);root.AppendChild(xe1);//添加到<bookstore>节点中
xmlDoc.Save("bookstore.xml");
//===============================================
结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>2、修改节点:将genre属性值为“李赞红“的节点的genre值改为“update李赞红”,将该节点的子节点<author>的文本修改为“亚胜”。
XmlNodeList nodeList= xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="李赞红")//如果genre属性值为“李赞红”
{xe.SetAttribute("genre","update李赞红");//则修改该属性为“update李赞红”
XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//遍历
{
XmlElement xe2=(XmlElement)xn1;//转换类型
if(xe2.Name=="author")//如果找到
{
xe2.InnerText="亚胜";//则修改
break;//找到退出来就可以了
}
}
break;
}
}xmlDoc.Save("bookstore.xml");//保存。
//==================================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book genre="fantasy" ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book genre="update李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>亚胜</author>
<price>58.3</price>
</book>
</bookstore>3、删除 <book genre="fantasy" ISBN="2-3631-4">节点的genre属性,删除 <book genre="update李赞红" ISBN="2-3631-4">节点。
XmlNodeList xnl=xmlDoc.SelectSingleNode("bookstore").ChildNodes;foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;
if(xe.GetAttribute("genre")=="fantasy")
{
xe.RemoveAttribute("genre");//删除genre属性
}
else if(xe.GetAttribute("genre")=="update李赞红")
{
xe.RemoveAll();//删除该节点的全部内容
}
}
xmlDoc.Save("bookstore.xml");
//===========================================
最后结果为:
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book ISBN="2-3631-4">
<title>Oberon's Legacy</title>
<author>Corets, Eva</author>
<price>5.95</price>
</book>
<book>
</book>
</bookstore>4、显示所有数据。
XmlNode xn=xmlDoc.SelectSingleNode("bookstore");XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl)
{
XmlElement xe=(XmlElement)xnf;
Console.WriteLine(xe.GetAttribute("genre"));//显示属性值
Console.WriteLine(xe.GetAttribute("ISBN"));XmlNodeList xnf1=xe.ChildNodes;
foreach(XmlNode xn2 in xnf1)
{
Console.WriteLine(xn2.InnerText);//显示子节点点文本
}
} -
读写xml java_Java如何读写xml文件?
2021-03-05 21:44:17小编典典这是一个快速的DOM示例,显示了如何使用dtd读写简单的xml文件:UserAuthorAdmin和dtd:首先导入这些:import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.*;import ...小编典典
这是一个快速的DOM示例,显示了如何使用dtd读写简单的xml文件:
User
Author
Admin
和dtd:
首先导入这些:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
这是你需要的一些变量:
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList rolev;
这是一个阅读器(字符串xml是你的xml文件的名称):
public boolean readXML(String xml) {
rolev = new ArrayList();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
And here a writer:
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue在这里:
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
添加一些访问器和更改器,你就完成了!
2020-03-01
-
Unity3d如何读写XML文件
2015-07-25 14:14:24今天顺便学习下unity3d下如何读写XML文件@@@@@@@@@@@@@ 1、首先搭建好一个场景。如图: 场景中的Sphere是要进行操作的对象,为了测试XML的读写的准确性,我对Sphere(MeshFilter)的Mesh属性的网格顶点的信息进行...今天顺便学习下unity3d下如何读写XML文件@@@@@@@@@@@@@
1、首先搭建好一个场景。如图:
场景中的Sphere是要进行操作的对象,为了测试XML的读写的准确性,我对Sphere(MeshFilter)的Mesh属性的网格顶点的信息进行读取和保存。
XmlTest是我要测试的脚本,把它拖到摄像机对象上就可以了。
2、下面对代码进行编写
using UnityEngine;
using System.Collections;
using System.IO;
using System.Xml;
using System.Collections.Generic;
public class XmlTest : MonoBehaviour {
//球对象
public GameObject _sphere;
//网格对象
public Mesh myMesh;
void Awake()
{
//找到球对象
_sphere = GameObject.Find("Sphere");
myMesh = _sphere.GetComponent<MeshFilter>().mesh;
}
// Use this for initialization
void Start () {
//1、首先生成Xml文件
//WriteXML();
//2、对Sphere的Mesh进行变形(按下Q键)
/*
Vector3[] vertices = myMesh.vertices;
for (int i = 0; i < vertices.Length; i++)
{
vertices[i] = new Vector3(3 * vertices[i].x, vertices[i].y, 3 * vertices[i].z);
}
myMesh.vertices = vertices;
myMesh.RecalculateBounds();
*/
//3、对Sphere的Mesh进行还原(按下W键)
ReadXML();
Vector3[] vertices = myMesh.vertices;
for (int i = 0; i < vertices.Length; i++)
{
vertices[i] = listDic[i].Value;
Debug.Log(listDic[i].Value);
}
myMesh.vertices = vertices;
myMesh.RecalculateBounds();
}
private void WriteXML()
{
//保存Xml文件的路径
string _path = Application.dataPath + @"\myTest\writeXml.xml";
if (File.Exists(_path))
return;
XmlDocument _newXml = new XmlDocument();
//根节点
XmlElement _nodeRoot = _newXml.CreateElement("VerticesRoot");
//遍历网格的顶点信息
for (int i = 0; i < myMesh.vertices.Length; i++)
{
XmlElement _tempNode = _newXml.CreateElement("VecElectment" + i);
_tempNode.SetAttribute("Vector3", myMesh.vertices[i].ToString());
_tempNode.SetAttribute("Index", i.ToString());
_nodeRoot.AppendChild(_tempNode);
}
_newXml.AppendChild(_nodeRoot);
_newXml.Save(_path);
}
private void ReadXML()
{
string _path = Application.dataPath + @"\myTest\writeXml.xml";
if (!File.Exists(_path))
return;
listDic.Clear();
XmlDocument _newXml = new XmlDocument();
_newXml.Load(_path);
XmlElement _nodeRoot = (XmlElement)_newXml.SelectSingleNode("VerticesRoot");
XmlNodeList _nodeList = _nodeRoot.ChildNodes;
for (int i = 0; i < _nodeList.Count; i++)
{
XmlElement _node = (XmlElement)_nodeList[i];
string _str = _node.GetAttribute("Vector3");
//对"(x,y,z)"进行分割
string[] _strArr = _str.Split('(', ',', ')');
KeyValuePair<int, Vector3> _dic = new KeyValuePair<int, Vector3>(int.Parse(_node.GetAttribute("Index")), new Vector3(float.Parse(_strArr[1]), float.Parse(_strArr[2]), float.Parse(_strArr[3])));
listDic.Add(_dic);
}
}
//保存读取的节点信息
private List<KeyValuePair<int, Vector3>> listDic = new List<KeyValuePair<int, Vector3>>();
}1、变形前
2、变形后
3、还原的会变形,还请大神指教,读取数据没问题
-
java 写xml_JAVA如何写XML文件
2021-02-27 08:10:04参考:import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.w3c.dom.Node;import org.w3c.dom.... -
如何使用dom4j如何读写xml文件
2017-08-06 17:09:54读取XML文件主要代码:SAXReader reader = new SAXReader(); Document document = reader.read(xmlFile);要读取的xml文件内容<?xml version="1.0" encoding="UTF-8"?> <name>Tom <age>11 实现具体代 -
Android Java 如何读写XML文件
2015-03-23 17:58:48使用 XmlPullParserFactory 构建XmlSerializer,然后对XML文件进行写是相当容易的,基本的步骤详见下面代码: package com.test.mytest; import java.io.File; import java.io.FileWriter; import java.io.... -
asp.net如何读写xml文件
2015-07-15 14:04:07已知有一个XML文件(bookstore.xml)如下: 代码 Oberon's Legacy Corets, Eva 5.95 1、往节点中插入一个节点: 代码 XmlDocument xmlDoc = new Xm -
C++如何读写xml文件
2013-07-09 19:48:00#pragma once #include "persistable.h"#include "memento.h"#include<vector>#include <string>using namespace std;class CFGStudent:public xml_api::Persistable{public: CFGStudent(void); ~... -
c#如何读写xml文件
2008-03-07 12:28:00每一个程序员都能轻易地看懂一个XML文件,理解它包含的内容。 .NET中包含了很多支持XML的类,这些类使得程序员使用XML编程就如同理解XML文件一样简单。在这篇文章中,我将给出这样的一个类的使用示例,这个类就是... -
PHP如何写XML文件?
2012-08-19 13:27:54已有一个XML文件,代码如下: <?xml version="1.0" encoding="GB2312"?> <AppConfig> ...有一个PHP变量$phone,希望将xml文件中"Phone"标签中的内容换为$phone的值,该如何实现? -
请问C#如何读写XML文件?
2014-08-05 16:06:53象下面这段文件如何读取? <Base> <Continent name="亚洲"> <Country name="中国"> </Country> <Country name="日本"> </Country> </Continent> <... -
C#如何读写XML文件?
2006-09-19 11:23:00using System.Xml;using System.IO;using System.Collections;namespace XMLDemoCSharp{ class XMLDemoCSharp { //Change bookfile to point to a valid path on your system, or Main will -
C#如何读写xml文件(实例)(转)
2010-02-09 10:36:00本文来自CSDN博客,转载请标明出处:...每一个程序员都能轻易地看懂一个XML文件,理解它包含的内容。 .NET中包含了很多支持XML的类,这些类使得程序员使... -
java 写xml_java如何向xml文件写入内容?
2021-02-27 08:10:41展开全部我以前学dom解析的时候写了一个小例子,你参考参考packagecom.lhx.test;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjavax.... -
如何用JSON读写XML文件
2012-02-12 21:20:33如何用JSON读写XML文件 链接:http://c.gzl.name/archives/244 JSON我就不多解释了,需要更多信息的朋友请到json.org上查看。 在iPhone上访问网络内容是很必须的,而一些数据就需要以某种... -
读写Xml文件
2015-09-30 11:12:58Xml的主要功能是存储、数据传输,那么如何通过xml文件进行数据读写,是本文关注的重点。 Xml的读写方式分为两种,一种是面向事件的SAX方式,另一种是面向模型的DOM方式。我们常常用的dom4j读取就是SAX读取方式的... -
C# 读写XML文件
2021-02-03 15:36:03C#写XML文件 C#如何创建一个新的XML把代码中的数据写到XML中, 要求:不光要写元素内容,还有有属性的值。示例: <?xml version="1.0"?> <Product xmlns:xsi=... -
PHP读写XML文件
2012-02-08 10:20:01PHP读写XML文件author: MoreWindowsblog: http://blog.csdn.net/MoreWindowsKeyWord: PHP 解析XML DOMDocument XML文件操作 PHP可以方便的生成和读取XML文件。PHP主要通过DOMDocument、DOMElement和DOMNodeList... -
java 读写xml_java-如何读取和写入xml文件?
2021-02-12 10:05:37这是一个快速的DOM示例,显示了如何使用dtd读写简单的xml文件:UserAuthorAdmin和dtd:首先导入这些:import javax.xml.parsers.*;import javax.xml.transform.*;import javax.xml.transform.dom.*;import javax.xml... -
python写xml文件
2010-12-10 22:51:18自己整理的,用python写xml文件,还算比较全面,唯一的缺点就是不知道如何把有text的节点整在同一行 -
python写xml文件 数据量特别大_Python:如何在1中处理大量child的大型XML文件
2021-03-05 22:15:34您可以使用iterparse方法来处理大型xml文件。但是,文件的结构特别简单。使用iterparse将是不必要的复杂。在我将在一个脚本中提供两个答案。我通过演示如何使用lxml解析xml中的行来直接回答您的问题,并且我提供了我...