asp.net操作xml

1.xml文档Products.xml

 <?xml version="1.0" encoding="utf-8"?>
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.pro.org/2001/products" xsi:schemaLocation="http://www.pro.org/2001/products products.xsd">
<item belong="数码">
<id>1</id>
<name>手机</name>
<price>1000</price>
</item>
<item belong="服装">
<id>2</id>
<name>男装</name>
<price>200</price>
</item>
<item belong="食品">
<id>3</id>
<name>黄瓜</name>
<price>4</price>
</item>
</products>

 2.schema约束文档 products.xml

 <?xml version="1.0" encoding="utf-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.pro.org/2001/products" xmlns:pro="http://www.pro.org/2001/products" elementFormDefault="qualified">
<element name="products" type="pro:pro"></element>
<complexType name="pro">
<sequence>
<element name="item" maxOccurs="unbounded">
<complexType>
<sequence>
<element name="id" type="string"></element>
<element name="name" type="string"></element>
<element name="price">
<simpleType>
<restriction base="float">
<maxExclusive value="10000"></maxExclusive>
<minInclusive value="0"></minInclusive>
</restriction>
</simpleType>
</element>
</sequence>
<attribute name="belong" type="string"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</schema>

3.定义实体类 DBPro.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; /// <summary>
///DBPro 的摘要说明
/// </summary>
public class DBPro
{
string belong;
string id;
string name;
string price;
public DBPro(string belong,string id,string name,string price)
{
this.belong = belong;
this.id = id;
this.name = name;
this.price = price;
}
public string Belong
{
get { return belong; }
set { belong = value; }
}
public string ID
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set{name=value;}
}
public string Price
{
get { return price; }
set { price = value; }
}
}

4.新建一个web窗体Defaut.aspx,在Default.aspx.cs中编写核心代码

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ //选择方法进行测试
//SearchXml();
DBPro pro = new DBPro("家电","10", "电视", "3999");
AddToXml(pro);
//UpdateOneXml(pro);
//DeleteXml("10");
}
/// <summary>
/// 遍历xml文档
/// </summary>
/// <param name="pro"></param>
private void SearchXml()
{
//提取xml文档
XmlDocument xd = new XmlDocument();
xd.Load(System.Web.HttpContext.Current.Server.MapPath("Products.xml"));
//获取根节点
XmlNode root = xd.DocumentElement;
//获取节点列表
XmlNodeList items = root.ChildNodes;
//遍历item项
Response.Write("<pre>");
foreach (XmlNode item in items)
{
//输出属性
Response.Write(item.Attributes["belong"].Name + "=" + item.Attributes["belong"].InnerText);
//遍历输出子节点
foreach (XmlNode p in item)
{
Response.Write(p.Name + "=" + p.InnerText);
}
}
Response.Write("</pre>");
}
/// <summary>
/// xml添加
/// </summary>
/// <param name="pro"></param>
private void AddToXml(DBPro pro)
{
//提取xml文档
XmlDocument xd = new XmlDocument();
xd.Load(System.Web.HttpContext.Current.Server.MapPath("Products.xml"));
//获取根节点
XmlNode root = xd.DocumentElement;
//创建元素
XmlElement newItem = xd.CreateElement("item");
XmlElement newID = xd.CreateElement("id");
XmlElement newName = xd.CreateElement("name");
XmlElement newPrice = xd.CreateElement("price");
//配置参数
newItem.SetAttribute("belong", pro.Belong);
newID.InnerText = pro.ID;
newName.InnerText = pro.Name;
newPrice.InnerText = pro.Price;
//装配
root.AppendChild(newItem);
newItem.AppendChild(newID);
newItem.AppendChild(newName);
newItem.AppendChild(newPrice);
xd.Save(System.Web.HttpContext.Current.Server.MapPath("Products.xml"));
}
/// <summary>
/// 修改xml一项
/// </summary>
/// <param name="pro"></param>
private void UpdateOneXml(DBPro pro)
{
//提取xml文档
XmlDocument xd = new XmlDocument();
xd.Load(System.Web.HttpContext.Current.Server.MapPath("Products.xml"));
//获取根节点
XmlNode root = xd.DocumentElement;
//获取节点列表
XmlNodeList items = root.ChildNodes;
//遍历节点列表
foreach (XmlNode item in items)
{
//遍历item
foreach (XmlNode p in item)
{
if (p.Name == "id" && p.InnerText == pro.ID)
{
item.Attributes["belong"].InnerText = pro.Belong;
p.NextSibling.InnerText = pro.Name;
p.NextSibling.NextSibling.InnerText = pro.Price;
}
}
}
}
/// <summary>
/// 删除xml一项
/// </summary>
/// <param name="pro"></param>
private void DeleteXml(string id)
{
//提取xml文档
XmlDocument xd = new XmlDocument();
xd.Load(System.Web.HttpContext.Current.Server.MapPath("Products.xml"));
//获取根节点
XmlNode root = xd.DocumentElement;
//获取节点列表
XmlNodeList items = root.ChildNodes;
//遍历节点列表
foreach (XmlNode item in items)
{
//遍历item
foreach (XmlNode p in item)
{
if (p.Name == "id" && p.InnerText == id)
{
root.RemoveChild(item);
}
}
}
}
}

此处应注意:用XMLDocument添加元素,遇到了这样一个问题:
当根节点具有 xmlns 属性时,用 XMLDocument 创建子元素时如果不指定 xmlns 或指定 xmlns 为 null 时,子元素将自动具有 xmlns="" 属性

<item belong="家电" xmlns="">
    <id>10</id>
    <name>电视</name>
    <price>3999</price>
  </item>
问题原因:

当父节点具有 xmlns 属性时,子节点必须指定 xmlns 属性,仅当子节点的 xmnls 属性与父节点相同时,子节点才不显示 xmlns 属性,最终就不会在 .xml 文件中显示出来

解决办法:

XmlElement newItem = xd.CreateElement("item",xd.DocumentElement.NamespaceURI);
        XmlElement newID = xd.CreateElement("id",xd.DocumentElement.NamespaceURI);
        XmlElement newName = xd.CreateElement("name",xd.DocumentElement.NamespaceURI);
        XmlElement newNumber = xd.CreateElement("number",xd.DocumentElement.NamespaceURI);

在每一个下级节点,都要继续指定命名空间,否则仍会出现 xmlns="" 属性。

///新手上道,若有不足或错误之处,敬请各位大神批评指正!

asp.net操作xml(增删查改)的更多相关文章

  1. linq to xml 增删查改

    一.XML基本概述 XML文件是一种常用的文件格式,例如WinForm里面的app.config以及Web程序中的web.config文件,还有许多重要的场所都有它的身影.Xml是Internet环境 ...

  2. springboot使用RestHighLevelClient7简单操作ElasticSearch7增删查改/索引创建

    本次操作是在  Windows上安装ElasticSearch7  进行操作 导入依赖 <?xml version="1.0" encoding="UTF-8&qu ...

  3. XML 增删查改

    <?xml version="1.0" encoding="utf-8"?> <users> <person name=" ...

  4. C# xml增删查改

    C# XML XmlDocument 添加命名空间: using System.Xml; 定义公共对象: XmlDocument xmldoc ; XmlNode xmlnode ; XmlEleme ...

  5. python操作mysql增删查改

    # coding=utf-8 ''' python操作mysql,需安装MySQLdb驱动 安装MySQLdb,请访问 http://sourceforge.net/projects/mysql-py ...

  6. c#中xml增删查改

    /// <summary> /// xml转list /// </summary> /// <typeparam name="T">目标对象&l ...

  7. Mysql 单表操作、增删查改(基础4)

    新建一个表,往里面插入数据. #新建一个表 mysql> create table test( -> id int, -> name varchar(20) -> );Quer ...

  8. ASP.NET动态的网页增删查改

    动态页面的增删查改,不多说了,直接上代码 跟前面的一般处理程序一样我上用的同一套三层,只是UI层的东西不一样,在纠结着要不要重新在上一次以前上过的代码: 纠结来纠结去,最后我觉得还上上吧,毕竟不上为我 ...

  9. Mybatis基础配置及增删查改操作

    一.简介 平时我们都用JDBC访问数据库,除了需要自己写SQL之外,还必须操作Connection, Statement, ResultSet 这些其实只是手段的辅助类. 不仅如此,访问不同的表,还会 ...

随机推荐

  1. TreeGrid( 树形表格)

    本节课重点了解 EasyUI 中 TreeGrid(树形表格)组件的使用方法,这个组件依赖于DataGrid(数据表格)组件 一. 加载方式//建立一个 JSON 文件[{"id" ...

  2. C#。4 数组

    一.跳出循环的俩个关键字 1.break与continue.        这两个关键字一般放在循环的花括号里面使用.break——结束整个循环.continue——结束本次循环,进入下次循环. br ...

  3. JQuery中常用的 属性选择器

    jQuery中使用$()作为选择符极大提高工作效率以及方便快捷;一些常用属性的选择器由以下几种 1) $('#id') id选择器 2) $('.class') css选择器,class类名 3) $ ...

  4. C#socket通讯两个最经典错误解决方案

    1.经典错误之 无法访问已释放的对象. 对象名:“System.Net.Sockets.Socket”     (1).问题现场   (2).问题叙述 程序中的某个地方调用到了socket.close ...

  5. javascript返回顶部几种代码总结

    纯js代码 /** * 回到页面顶部 * @param acceleration 加速度 * @param time 时间间隔 (毫秒) **/ function goTop(acceleration ...

  6. TEXT类型

    创建文档document.createTextNode("直接就是想打的文本") 然后用 appendChild() 再然后就是一些其他的方法 appendData(a)在a里面直 ...

  7. 清北学堂 Pa

    PA[题目描述]汉诺塔升级了:现在我们有?个圆盘和?个柱子,每个圆盘大小都不一样,大的圆盘不能放在小的圆盘上面,?个柱子从左到右排成一排.每次你可以将一个柱子上的最上面的圆盘移动到右边或者左边的柱子上 ...

  8. Python一路走来 RabbitMQ

    一:介绍:(induction) Rabbitmq 是一个消息中间件.他的思想就是:接收和发送消息.你可以把它想成一个邮政局.当你把你的邮件发送到邮箱的,首先你需要确认的是:邮政员先生能把你的邮件发送 ...

  9. java练习-滚动文字

    <marquee direction="left" onMouseOver="this.scrollAmount=5" onMouseOut=" ...

  10. Xcode本地文件 提交svn 的明细

    XXXXX.xcscmblueprint  这个文件不用提交svn