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. sqlserver 大数据量的insert、delete操作优化

    http://blog.csdn.net/lanyuzhen/article/details/7547476 --大批量导出orders表:insert DBCC DROPCLEANBUFFERS   ...

  2. php中array_slice和array_splice函数解析方式方法

    array_slice array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_k ...

  3. jQuery左右循环滚动图片特效

    在线演示 本地下载

  4. Leetcode821.Shortest Distance to a Character字符的最短距离

    给定一个字符串 S 和一个字符 C.返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组. 示例 1: 输入: S = "loveleetcode", C ...

  5. HDU 4193

    本题思路:用sum[]数组维护前缀和, 当然这里需要把原数组扩大为原来的两倍. 然后对于任意一个长度为n的区间 k.....k+n-1,如果有该区间内的最小值大于等于sum[k-1]那么该种情况就符合 ...

  6. java读取properties文件总结

    一.java读取properties文件总结 在java项目中,操作properties文件是经常要做的,因为很多的配置信息都会写在properties文件中,这里主要是总结使用getResource ...

  7. Java注解初步了解 2016-07-24 22:20 240人阅读 评论(21) 收藏

    Java注解又称Java标注,是Java语言5.0版本开始支持加入源代码的特殊语法元数据. Java语言中的类.方法.变量.参数和包等都可以被标注.Java标注和Javadoc不同,标注有自反性.在编 ...

  8. el标签 2016-06-05 21:39 477人阅读 评论(15) 收藏

    JSP EL语言定义 E L(Expression Language) 目的:为了使JSP写起来更加简单. 表达式语言的灵感来自于 ECMAScript 和 XPath 表达式语言,它提供了在 JSP ...

  9. shared_ptr的线程安全性

    一: All member functions (including copy constructor and copy assignment) can be called by multiple t ...

  10. docker保存容器的修改

    docker保存容器修改 通过在容器中运行某一个命令,可以把对容器的修改保存下来, 这样下次可以从保存后的最新状态运行该容器.docker中保存状态的过程称之为committing, 它保存的新旧状态 ...