C# 操作XML学习笔记
1. Customers.xml
<?xml version="1.0" encoding="utf-8"?>
<cust:customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customers.xsd"
xmlns:cust="http://asn.test.xsd/customers">
<cust:customer customerid="1">
<cust:firstname>John</cust:firstname>
<cust:lastname>Cranston</cust:lastname>
<cust:homephone>(445) 269-9857</cust:homephone>
<cust:notes><![CDATA[He registed as our member since 1990. John has nice credity. He is a member of Custom International.]]></cust:notes>
</cust:customer>
<cust:customer customerid="2">
<cust:firstname>Annie</cust:firstname>
<cust:lastname>Loskar</cust:lastname>
<cust:homephone>(445) 269-9482</cust:homephone>
<cust:notes><![CDATA[Annie registed as our member since 1984. He became our VIP customer in 1996.]]></cust:notes>
</cust:customer>
<cust:customer customerid="3">
<cust:firstname>Bernie</cust:firstname>
<cust:lastname>Christo</cust:lastname>
<cust:homephone>(445) 269-3412</cust:homephone>
<cust:notes><![CDATA[Bernie registed as our member since June 2010. He is a new member.]]></cust:notes>
</cust:customer>
<cust:customer customerid="4">
<cust:firstname>Ernestine</cust:firstname>
<cust:lastname>Borrison</cust:lastname>
<cust:homephone>(445) 269-7742</cust:homephone>
<cust:notes><![CDATA[Ernestine registed as our member since Junl 2010. She is a new member.]]></cust:notes>
</cust:customer>
<cust:customer customerid="5">
<cust:firstname>asn</cust:firstname>
<cust:lastname>asn</cust:lastname>
<cust:homephone>(445) 269-9857</cust:homephone>
<cust:notes><![CDATA[He registed as our member since 1990. John has nice credity. He is a member of Custom International.]]></cust:notes>
</cust:customer>
</cust:customers>
2. 操作类
class Books
{ private static string booksXsdPath = getProjectPath() + "files\\books.xsd";
private static string booksXmlPath = getProjectPath() + "files\\booksSchemaFail.xml"; private static void GenCustomerXSD()
{ XmlSchema _schema = new XmlSchema();
//定义简单类型 NameSimpleType
XmlSchemaSimpleType _nameType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction _nameTypeRes = new XmlSchemaSimpleTypeRestriction();
_nameTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet _nameFacet1 = new XmlSchemaMaxLengthFacet();
_nameFacet1.Value = "";
XmlSchemaMinLengthFacet _nameFacet2 = new XmlSchemaMinLengthFacet();
_nameFacet2.Value = "";
_nameTypeRes.Facets.Add(_nameFacet1);
_nameTypeRes.Facets.Add(_nameFacet2); _nameType.Content = _nameTypeRes; //定义简单类型 PhoneSimpleType
XmlSchemaSimpleType _phoneType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction _phoneTypeRes = new XmlSchemaSimpleTypeRestriction();
_phoneTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
XmlSchemaMaxLengthFacet _phoneFacet1 = new XmlSchemaMaxLengthFacet();
_phoneFacet1.Value = "";
_phoneTypeRes.Facets.Add(_phoneFacet1); _phoneType.Content = _phoneTypeRes; // 定义简单类型 NotesSimpleType
XmlSchemaSimpleType _notesType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction _notesTypeRes = new XmlSchemaSimpleTypeRestriction();
_notesTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); XmlSchemaMaxLengthFacet _notesFacet1 = new XmlSchemaMaxLengthFacet();
_notesFacet1.Value = ""; _notesTypeRes.Facets.Add(_notesFacet1);
_notesType.Content = _notesTypeRes; // 定义CustomerType复杂类型
XmlSchemaComplexType _customerType = new XmlSchemaComplexType(); XmlSchemaSequence _sequence = new XmlSchemaSequence(); XmlSchemaElement _firstName = new XmlSchemaElement();
_firstName.Name = "firstName";
_firstName.SchemaType = _nameType; XmlSchemaElement _lastName = new XmlSchemaElement();
_lastName.Name = "lastName";
_lastName.SchemaType = _nameType; XmlSchemaElement _homePhone = new XmlSchemaElement();
_homePhone.Name = "homePhone";
_homePhone.SchemaType = _phoneType; XmlSchemaElement _notes = new XmlSchemaElement();
_notes.Name = "notes";
_notes.SchemaType = _notesType; _sequence.Items.Add(_firstName);
_sequence.Items.Add(_lastName);
_sequence.Items.Add(_homePhone);
_sequence.Items.Add(_notes); _customerType.Particle = _sequence; // 定义属性customerId
XmlSchemaAttribute _customerId = new XmlSchemaAttribute();
_customerId.Name = "customerId";
_customerId.SchemaTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");
_customerId.Use = XmlSchemaUse.Required;
_customerType.Attributes.Add(_customerId); // 定义 CustomersType 复杂类型
XmlSchemaComplexType _customersType = new XmlSchemaComplexType();
XmlSchemaSequence _sq = new XmlSchemaSequence();
XmlSchemaElement _customer = new XmlSchemaElement();
_customer.Name = "customer";
_customer.SchemaType = _customerType;
_customer.MinOccurs = ;
_customer.MaxOccursString = "unbounded";
_sq.Items.Add(_customer);
_customersType.Particle = _sq; // 定义 customers 元素
XmlSchemaElement _customers = new XmlSchemaElement();
_customers.Name = "customers";
_customers.SchemaType = _customersType; // 把 customers 元素, 添加到模式_schema下
_schema.Items.Add(_customers); try
{
XmlSchemaSet _set = new XmlSchemaSet();
_set.Add(_schema);
_set.Compile();
}
catch (Exception ex)
{
Console.WriteLine("模式编译失败:" + ex.Message);
} XmlTextWriter _write = new XmlTextWriter(getProjectPath() + "files\\customers.xsd", System.Text.Encoding.UTF8);
_schema.Write(_write);
_write.Close(); } /// <summary>
/// 通过 XmlReader 在加载XML文档时同时加载XSD进行校验
/// </summary>
private static void BooksValidationByXmlReader()
{
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("urn:bookstore-schema", booksXsdPath); XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = schemaSet;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack); // 在加载XML文档时同时,加载XSD,进行校验
XmlReader reader = XmlReader.Create(booksXmlPath, settings); while (reader.Read()) ;
/*
* Validation Error: The element 'book' in namespace 'urn:bookstore-schema'
* has invalid child element 'author' in namespace 'urn:bookstore-schema'.
*
* List of possible elements expected: 'title' in namespace 'urn:bookstore-schema'.
*
* Validation Error: The element 'author' in namespace 'urn:bookstore-schema'
* has invalid child element'name' in namespace 'urn:bookstore-schema'.
*
* List of possible elements expected: 'first-name' in namespace 'urn:bookstore-schema'.
*
* */
} /// <summary>
/// 通过XmlDocument类的 Validate() 方法,验证XML数据是否符合指定的XSD模式文件
/// </summary>
private static void BooksValidationByXmlDocument()
{
XmlDocument doc = new XmlDocument(); /*
* doc.LoadXml() 从指定的xml string 字符串中解析XML DOM
* */
doc.Load(booksXmlPath);
doc.Schemas.Add("urn:bookstore-schema", booksXsdPath);
doc.Validate(ValidationCallBack); } /// <summary>
/// 使用XPathDocument遍历XML文档
/// </summary>
private static void XPathNavigatorTravel()
{
XPathDocument _doc = new XPathDocument(getProjectPath() + "files\\Customers.xml");
XPathNavigator _navigator = _doc.CreateNavigator(); _navigator.MoveToRoot(); // 移到文档的根(文档根下有: XML声明, XML处理指令, XML根元素customers )
_navigator.MoveToFirstChild(); // 移到XML根元素customers if (_navigator.HasChildren)
{
_navigator.MoveToFirstChild(); // 移到根元素customers的customer子元素 do
{
string _id = _navigator.GetAttribute("customerid", "http://asn.test.xsd/customers");
Console.WriteLine("Customer ID: " + _id); _navigator.MoveToFirstChild(); // 移动到customer元素的firstname子元素 do
{
Console.WriteLine(" " + _navigator.Name + ": " + _navigator.Value);
} while(_navigator.MoveToNext()); _navigator.MoveToParent();
}
while (_navigator.MoveToNext());
} } /// <summary>
/// 使用 XPathNavigator 类的 Select()方法, 选择XML文档节点
/// </summary>
private static void XPathNavigatorSelect()
{
XPathDocument _doc = new XPathDocument(getProjectPath() + "files\\Customers.xml");
XPathNavigator _navigator = _doc.CreateNavigator();
XmlNamespaceManager _manager = new XmlNamespaceManager(_navigator.NameTable);
_manager.AddNamespace("cust", "http://asn.test.xsd/customers"); XPathNodeIterator _iterator = _navigator.Select("//cust:customer[@customerid=2]", _manager); Console.WriteLine("选中的节点个数:" + _iterator.Count); StringBuilder resultsb = new StringBuilder();
int number = ;
if (_iterator.Count > )
{
while (_iterator.MoveNext())
{
resultsb.Append("第" + (number++) + "个customer节点:" + _iterator.Current.OuterXml);
}
}
else
{
resultsb.Append("无匹配的节点");
} Console.WriteLine(resultsb.ToString()); } static void Main(string[] args)
{ //BooksValidationByXmlDocument(); //GenCustomerXSD(); XPathNavigatorSelect(); } /// <summary>
/// 校验出错时的回调方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
} public static string getProjectPath()
{
string basePath = AppDomain.CurrentDomain.BaseDirectory; // \\XmlTest\\bin\\Debug\\
string projectPath = basePath.Substring(, basePath.IndexOf("bin"));
return projectPath;
}
}
C# 操作XML学习笔记的更多相关文章
- delphi操作xml学习笔记 之一 入门必读
Delphi 对XML的支持---TXMLDocument类 Delphi7 支持对XML文档的操作,可以通过TXMLDocument类来实现对XML文档的读写.可以利用TXMLDocum ...
- PHP操作xml学习笔记之增删改查(2)—删、改、查
xml文件 <?xml version="1.0" encoding="utf-8"?><班级> <学生> ...
- PHP操作xml学习笔记之增删改查(1)—增加
xml文件 <?xml version="1.0" encoding="utf-8"?><班级> <学生> ...
- XML学习笔记
XML学习笔记 第一部分:XML简介 我们经常可以听到XML.HTML.XHTML这些语言,后两者比较清楚,一直不是很明白XML是什么,这里做一个总结. XML(eXtensible Markup L ...
- PHP操作MongoDB学习笔记
<?php/*** PHP操作MongoDB学习笔记*///*************************//** 连接MongoDB数据库 **////*************** ...
- Flas-SQLAchemy数据库操作使用学习笔记
Flas-SQLAchemy数据库操作使用学习笔记 Flask-SQLALchemy 是一个给你的应用添加 SQLALchemy 支持的 Flask 扩展.SQLALchemy 是Python语言的S ...
- XML学习笔记(2)--dom4j操作XML
1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析 ...
- Python之xml学习笔记
XML处理模块 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,至今很多传统公司如金融行业的很多系统的接口还主要是xml. xml的格式如下,就是通过&l ...
- C#操作XML学习之创建XML文件的同时新建根节点和子节点(多级子节点)
最近工作中遇到一个问题,要求创建一个XML文件,在创建的时候要初始化该XML文档,同时该文档打开后是XML形式,但是后缀名不是.在网上找了好些资料没找到,只能自己试着弄了一下,没想到成功了,把它记下来 ...
随机推荐
- 第一周<导学>
导学 欧氏距离 平方 曼哈顿距离 一次方 马氏距离 协方差(先标准化再计算距离)\(d(x_{i},x_{j})=\sqrt{(x_{i}-x_{j})^{T}s^{-1}(x_{i}-x{j})}\ ...
- PHP学习(运算符)
PHP运算符一般分为算术运算符.赋值运算符.比较运算符.三元运算符.逻辑运算符.字符串连接运算符.错误控制运算符. 算术运算符 主要是用于进行算术运算的,例如:加法运算.减法运算.乘法运算.除法运算 ...
- 初识Django(DNS原理及web框架)
DNS的原理 假设www.abc.com的主机要查询www.xyz.abc.com的服务器ip地址. 知识点 1.hosts文件:以静态映射的方式提供IP地址与主机名的对照表,类似ARP表 2.域:a ...
- thinkphp常用的一些函数
$this->display ( "Public:login" ); import ( 'Wechat', APP_PATH . 'Common/Wechat', '.cla ...
- 纯CSS3打造圆形菜单
原理是使用相对定位和绝对定位确定圆形菜单位置. 使用伪类选择器E:hover确定悬浮时候的效果,动画效果用CSS3的transition属性. 大概代码如下. html: <div id=&qu ...
- __defineGetter__和__defineSetter__在日期中的应用
日期函数每次取年月日都要调用Date的函数,有点麻烦,通过__defineGetter__可以处理一下,就能通过Date的实例对象直接获取年月日,例如 date.year获取日期对象date的年份.月 ...
- C# —— 访问修饰符
1.public 公有的,任何代码均可以访问,应用于所有类或成员. 2.internal 内部的,只能在当前程序集中使用,应用于所有类或成员. 3.protected internal 受保护的内部成 ...
- Kafka 简易教程
1.初识概念 Apache Kafka是一个分布式消息发布订阅系统. TopicKafka将消息种子(Feed)分门别类, 每一类的消息称之为话题(Topic). Producer发布消息的对象称之为 ...
- IoT SaaS加速器——助力阿尔茨海默病人护理
场景介绍 阿尔茨海默病,是导致中老年人认知功能障碍的最常见疾病之一,是发生在老年期及老年前期的一种原发性退行性脑病.据估计,全世界痴呆症患者数量为4700万,到2030年将达到7500万人.痴呆症患者 ...
- HZOJ 矩阵游戏
大水题一个,然而由于两颗线段树的阴影我死了…… 算法一:对于50%的数据: 送分,直接一个一个乘,时间复杂度O(KN). 算法二:对于80%的数据:如果我们不一个一个乘,将第i行的和乘x ,第j列的和 ...