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. 打开新窗口(window.open)

    open() 方法可以查找一个已经存在或者新建的浏览器窗口. 语法: window.open([URL], [窗口名称], [参数字符串]) 参数说明: URL:可选参数,在窗口中要显示网页的网址或路 ...

  2. Asp.Net WebAPI Get提交、Post提交处理

    1.启用跨域提交 <system.webServer> <httpProtocol> <customHeaders> <add name="Acce ...

  3. (转)ip地址,手机ip查询

    页面地址:http://www.ip138.com/ 外链地址(实际主页面里面有)http://www.ip138.com/iplink.htm 外链地址里面的内容: <FORM METHOD= ...

  4. .net web api 的route理解

    .NET web api 的特性是和MVC一样,通过Route 来控制action的访问方式.Route匹配规则是个奇特的方式,首先看一段Route的模板 Routes.MapHttpRoute( n ...

  5. IDirect3DDevice9::Clear

    在绘制每一帧图形前都要先清空视区,即清空渲染目标表面上的视区矩形的内容:颜色缓冲区.深度缓冲区或者模板缓冲区. HRESULT Clear(  [in]  DWORD Count,           ...

  6. mybatis入门,基本案例和xml讲解

    mybatis入门 先举一个入门案例 1)创建一个mybatis-day01这么一个javaweb工程或java工程 2)导入mybatis和mysql/oracle的jar包到/WEB-INF/li ...

  7. jquery实现简单鼠标经过图片预览效果

    html结构:<div class="prebtn"><img src=""/></div> css代码:#preview{ ...

  8. 转载:Tomcat多数据源配置方法

    转载网址:http://blog.sina.com.cn/s/blog_53803b7b010144u5.html 关于在TOMCAT下配置多数据源,网上有很多方式,但是感觉也很混乱,俺只说俺们使用的 ...

  9. ROBOTS.TXT屏蔽笔记、代码、示例大全

    自己网站的ROBOTS.TXT屏蔽的记录,以及一些代码和示例: 屏蔽后台目录,为了安全,做双层管理后台目录/a/xxxx/,蜘蛛屏蔽/a/,既不透露后台路径,也屏蔽蜘蛛爬后台目录 缓存,阻止蜘蛛爬静态 ...

  10. 关于Linux平台malloc的写时拷贝(延迟分配)【转】

    Linux内核定义了“零页面”(内容全为0的一个物理页,且物理地址固定),应用层的内存分配请求,如栈扩展.堆分配.静态分配等,分配线性地址后,就将页表项条目指向“零页面”(指定初始值的情况除外),这样 ...