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形式,但是后缀名不是.在网上找了好些资料没找到,只能自己试着弄了一下,没想到成功了,把它记下来 ...
随机推荐
- 学习JDK1.8集合源码之--Vector
1. Vector简介 Vector是JDK1.0版本就推出的一个类,和ArrayList一样,继承自AbstractList,实现了List.RandomAccess.Cloneable.java. ...
- 一句python,一句R︱python中的字符串操作、中文乱码、NaN情况
一句python,一句R︱python中的字符串操作.中文乱码.NaN情况 先学了R,最近刚刚上手Python,所以想着将python和R结合起来互相对比来更好理解python.最好就是一句pytho ...
- Redis、MPP、kafka 、MongDB简介
Redis :间值数据库,适合缓存用户Session会话与经常需要查的数据1.Redis集群,为什么在项目中使用集群 1.持久化,持久化是最简单的高可用方法(有时甚至不被归为高可用的手段),主要左右 ...
- PostgreSQL 给数组排序
PostgreSQL 支持数组,可是没有对数据内部元素进行排序的一个函数. 今天我分别用PLPGSQL和PLPYTHONU写了一个.演示样例表结构: t_girl=# \d test_array; ...
- iOS app发布流程
http://www.xuebuyuan.com/1980497.html http://blog.csdn.net/alincexiaohao/article/details/38725367 ap ...
- 洛谷 P2146 [NOI2015]软件包管理器 树链剖分
目录 题面 题目链接 题目描述 输入输出格式 输入格式: 输出格式: 输入输出样例 输入样例#1: 输出样例#1: 输入样例#2: 输出样例#2: 说明 说明 思路 AC代码 总结 题面 题目链接 P ...
- Codeforces 432C
题目链接 题意: 给出一个长度为n(n<=10^5)的数组a, 数组a是数字1到n的一种排列(打乱顺序). 每次可以选择两个数(不同)进行交换, 但是交换的条件是被选择的两个数的下标之差加1应 ...
- 使用 Markdown Flow 画流程图
使用 Markdown Flow 画流程图 好处是可以方便的使用 Git 管理版本 st=>start: 开始 e=>end: 结束 c1=>condition: A c2=> ...
- constexpr:编译期与运行期之间的神秘关键字
Scott Meyers在effective modern c++中提到“If there were an award for the most confusing new word in C++11 ...
- HDU 5673 Robot【卡特兰数】
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5673 题意: 有一个机器人位于坐标原点上.每秒钟机器人都可以向右移到一个单位距离,或者在原地不动.如 ...