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. Pyhton AES_cbc解密

    最近很多朋友问我加密解密有没有啥好推荐的方式,一般对AES的加密解密方式直接用在线加密或者解密就行,我为了方便测试,将网址以python脚本的形式写了出来,很简单的东西,2分钟搞定,随手记录一下~~ ...

  2. Leetcode2.Add Two Numbers两数相加

    给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入:(2 -& ...

  3. 如何在Liferay 7中用html显示页面

    liferay portlet默认的显示页面是view.jsp,虽然可以在jsp中用include标签包括html文件,但是如何直接通过修改配置文件让默认的显示页面为view.html呢? 1.用Li ...

  4. JavaScript--函数表达式与函数声明的区别

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. ios开发ARC,IBOutlets之strong与weak

    今天在写程序的时候,用IBOutlets连了一个自定义的控件,出现了问题,后面访问的时候,控件里有些subviews没有初始化好,取到的时候为nil, 程序里用了ARC, IBOutlets一连接上, ...

  6. More Effective C++: 02操作符

    05:谨慎定义类型转换函数 有两种函数允许编译器进行隐式类型转换:单参数构造函数(single-argument constructors)和隐式类型转换运算符.单参数构造函数是指只用一个参数即可以调 ...

  7. 2019-4-29-dotnet-通过-WMI-获取系统安装软件

    title author date CreateTime categories dotnet 通过 WMI 获取系统安装软件 lindexi 2019-04-29 12:18:59 +0800 201 ...

  8. UVA_10071:Back to High School Physics

    Language:C++ 4.8.2 #include<stdio.h> int main(void) { int v, t; while(scanf("%d%d", ...

  9. shell学习(16)- 压缩和解压缩命令tar和zip

    tar命令 [root@Linux ~]# tar [-cxtzjvfpPN] 文件与目录 .... 参数: -c :建立一个压缩文件的参数指令(create 的意思): -x :解开一个压缩文件的参 ...

  10. Ubuntu18.10创建软件图标

    解压下载包都/opt目录 创建并编辑/usr/share/applications/xxx.desktop [Desktop Entry] Encoding=UTF-8 Name=Pycharm Co ...