System.Xml
using
System.IO
namespace
WriteXml{classProgram{
static
void
Main(string[]
args){
addItem()//追加节点(数据)}privatestatic
void
addItem(){
XmlDocument
xmlDoc
=
new
XmlDocument()
xmlDoc.Load("titles.xml")//加载xml文件,路径未指定时默认在当前项目环境下
XmlNode
root
=
xmlDoc.SelectSingleNode("items")//选择要添加子节点的items节点
XmlElement
xe1
=
xmlDoc.createElement_x("item")//创建一个具有指定名称的子节点
xe1.SetAttribute("类别",
"张三")//设置item的属性
及属性值
xe1.SetAttribute("品质",
"老师")//
XmlElement
xmlsub1
=
xmlDoc.createElement_x("title")//创建一个具有指定名称的元素
xmlsub1.InnerText
=
"wahahha"//设置该元素的值
xe1.AppendChild(xmlsub1)//将该元素添加到item子节点的尾部
XmlElement
xmlsub2
=
xmlDoc.createElement_x("author")//创建一个具有指定名称的元素
xmlsub2.InnerText
=
"三毛"//设置该元素的值
xe1.AppendChild(xmlsub2)//将该元素添加到item子节点的尾部
XmlElement
xmlsub3
=
xmlDoc.createElement_x("芦稿Price")//创建一个具有指定名称的元素
xmlsub3.InnerText
=
"15.00"//设置该元素的值
xe1.AppendChild(xmlsub3)//将该元素添加到item子节点的尾部
root.AppendChild(xe1)//将创建的item子节点添加到items节点的尾部
这个是修改后的...private void AddXml(string url, string title, string description, string target, int btn)
{
XmlDocument xmlDoc = new XmlDocument()
xmlDoc.Load("../../XMLFile.xml") //加载xml文件
XmlNode rootXml = xmlDoc.SelectSingleNode("siteMapPath") //查询XML文件的根节点("siteMapPath")
XmlNode xn = rootXml.SelectSingleNode("siteMap") //查询节点("siteMap")
if (btn == 1)
{
XmlElement xe = xmlDoc.CreateElement("siteMap") //创建节点("siteMap")
//设置新建节点("siteMap")的相关属性
xe.SetAttribute("url", url)
xe.SetAttribute("title", title)
xe.SetAttribute("description", description)
xe.SetAttribute("target", target)
if (xn.Attributes["title"].Value.Equals("教学管理"))
{
rootXml.InsertAfter(xe, xn) //将新建的节点xe放置于xn节点后
}
}
else
{
XmlNodeList xnl = xn.SelectNodes("siteMapNode") //获取所有节点为"siteMapNode"的节点
foreach (XmlNode xnItem in xnl)
{
XmlElement xe = (XmlElement)xnItem//将子节点纯伍余类型转换为XmlElement类型
if (xe.GetAttribute("title").Equals("院系介绍"))//判断条件
{
XmlElement newXE = xmlDoc.CreateElement("siteMapChildNode")
newXE.SetAttribute("url", url)
newXE.SetAttribute("title"橘伏, title)
newXE.SetAttribute("description", description)
newXE.SetAttribute("target", target)
xnItem.AppendChild(newXE)
}
}
}
xmlDoc.Save("做滚../../XMLFile.xml")
}
private void button1_Click(object sender, EventArgs e)
{
this.AddXml("", "实践教学", "", "_self", 1)
MessageBox.Show("添加实践教学成功...")
}
private void button2_Click(object sender, EventArgs e)
{
this.AddXml("", "工商学院", "", "_self", 2)
MessageBox.Show("添加工商学院成功...")
}
应该就可以了, 你试看看吧.
呵呵O(∩_∩)O~ 赏分就算了, 回答你这个我也学到了东西. 呵呵
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)