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学习笔记的更多相关文章

  1. delphi操作xml学习笔记 之一 入门必读

    Delphi 对XML的支持---TXMLDocument类       Delphi7 支持对XML文档的操作,可以通过TXMLDocument类来实现对XML文档的读写.可以利用TXMLDocum ...

  2. PHP操作xml学习笔记之增删改查(2)—删、改、查

    xml文件 <?xml version="1.0" encoding="utf-8"?><班级>    <学生>       ...

  3. PHP操作xml学习笔记之增删改查(1)—增加

    xml文件 <?xml version="1.0" encoding="utf-8"?><班级>    <学生>       ...

  4. XML学习笔记

    XML学习笔记 第一部分:XML简介 我们经常可以听到XML.HTML.XHTML这些语言,后两者比较清楚,一直不是很明白XML是什么,这里做一个总结. XML(eXtensible Markup L ...

  5. PHP操作MongoDB学习笔记

    <?php/*** PHP操作MongoDB学习笔记*///*************************//**   连接MongoDB数据库  **////*************** ...

  6. Flas-SQLAchemy数据库操作使用学习笔记

    Flas-SQLAchemy数据库操作使用学习笔记 Flask-SQLALchemy 是一个给你的应用添加 SQLALchemy 支持的 Flask 扩展.SQLALchemy 是Python语言的S ...

  7. XML学习笔记(2)--dom4j操作XML

    1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析 ...

  8. Python之xml学习笔记

    XML处理模块 xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,至今很多传统公司如金融行业的很多系统的接口还主要是xml. xml的格式如下,就是通过&l ...

  9. C#操作XML学习之创建XML文件的同时新建根节点和子节点(多级子节点)

    最近工作中遇到一个问题,要求创建一个XML文件,在创建的时候要初始化该XML文档,同时该文档打开后是XML形式,但是后缀名不是.在网上找了好些资料没找到,只能自己试着弄了一下,没想到成功了,把它记下来 ...

随机推荐

  1. 学习es6

    #第一节 初始化项目 npm init -y 安装babel-cli npm install -g babel-cli npm install --save-dev babel-preset-es20 ...

  2. JS放在body与head中的不同

    放在body和head其实差不多的,只不过是文档解析的时间不同.浏览器解析html是从上到下的.如果把javascript放在head里的话,则先被解析,但这时候body还没有解析,所以$(#btn) ...

  3. Android Binder设计与实现 – 设计篇

    摘要 Binder是Android系统进程间通信(IPC)方式之一.Linux已经拥有管道,system V IPC,socket等IPC手段,却还要倚赖Binder来实现进程间通信,说明Binder ...

  4. JavaScript--for in循环访问属性用"."和[ ]的区别

    // for in 循环遍历对象的时候// 内部要访问属性的时候不能点语法访问,因为for in 的key是字符串格式// 可通过方括号实现访问 for(var key in manObj) { co ...

  5. SqlAlchemy的简单使用

    1.SQLAlchemy SQLAlchemy是python的一个通用的ORM框架 1.1 创建数据表 from sqlalchemy.ext.declarative import declarati ...

  6. laravle 事务

    DB::beginTransaction(); try{     $name = 'abc';     $result1 = Test::create(['name'=>$name]);     ...

  7. 【JZOJ4884】【NOIP2016提高A组集训第12场11.10】图的半径

    题目描述 mhy12345学习了树的直径,于是开始研究图的半径,具体来说,我们需要在图中选定一个地方作为中心,其中这个中心有可能在路径上. 而这个中心的选址需要能够使得所有节点达到这个中心的最短路里面 ...

  8. 【Mysql的那些事】数据库之ORM操作

    1:ORM的基础操作(必会) <1> all(): 查询所有结果 <2> filter(**kwargs): 它包含了与所给筛选条件相匹配的对象 <3> get(* ...

  9. LeetCode97 Interleaving String

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. (Hard) For example,Giv ...

  10. 防止chrome主页被篡改并设置为默认打开无痕浏览方式

    1. 找到chrome的快捷方式, 右击打开属性 2. 将目标框内容改为以下内容chrome.exe的目录位置 // ----- 引号中的内容为"PATH\Chrome\Applicatio ...