C# 操作XML学习笔记

1. Customers.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <cust:customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Customers.xsd"
 3            xmlns:cust="http://asn.test.xsd/customers">
 4     <cust:customer customerid="1">
 5         <cust:firstname>John</cust:firstname>
 6         <cust:lastname>Cranston</cust:lastname>
 7         <cust:homephone>(445) 269-9857</cust:homephone>
 8         <cust:notes><![CDATA[He registed as our member since 1990. John has nice credity. He is a member of Custom International.]]></cust:notes>
 9     </cust:customer>
10     <cust:customer customerid="2">
11         <cust:firstname>Annie</cust:firstname>
12         <cust:lastname>Loskar</cust:lastname>
13         <cust:homephone>(445) 269-9482</cust:homephone>
14         <cust:notes><![CDATA[Annie registed as our member since 1984. He became our VIP customer in 1996.]]></cust:notes>
15     </cust:customer>
16     <cust:customer customerid="3">
17         <cust:firstname>Bernie</cust:firstname>
18         <cust:lastname>Christo</cust:lastname>
19         <cust:homephone>(445) 269-3412</cust:homephone>
20         <cust:notes><![CDATA[Bernie registed as our member since June 2010. He is a new member.]]></cust:notes>
21     </cust:customer>
22     <cust:customer customerid="4">
23         <cust:firstname>Ernestine</cust:firstname>
24         <cust:lastname>Borrison</cust:lastname>
25         <cust:homephone>(445) 269-7742</cust:homephone>
26         <cust:notes><![CDATA[Ernestine registed as our member since Junl 2010. She is a new member.]]></cust:notes>
27     </cust:customer>
28     <cust:customer customerid="5">
29         <cust:firstname>asn</cust:firstname>
30         <cust:lastname>asn</cust:lastname>
31         <cust:homephone>(445) 269-9857</cust:homephone>
32         <cust:notes><![CDATA[He registed as our member since 1990. John has nice credity. He is a member of Custom International.]]></cust:notes>
33     </cust:customer>
34 </cust:customers>

2. 操作类

  1     class Books
  2     {
  3
  4
  5         private static string booksXsdPath = getProjectPath() + "files\\books.xsd";
  6         private static string booksXmlPath = getProjectPath() + "files\\booksSchemaFail.xml";
  7
  8
  9         private static void GenCustomerXSD()
 10         {
 11
 12             XmlSchema _schema = new XmlSchema();
 13             //定义简单类型 NameSimpleType
 14             XmlSchemaSimpleType _nameType = new XmlSchemaSimpleType();
 15
 16             XmlSchemaSimpleTypeRestriction _nameTypeRes = new XmlSchemaSimpleTypeRestriction();
 17             _nameTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
 18             XmlSchemaMaxLengthFacet _nameFacet1 = new XmlSchemaMaxLengthFacet();
 19             _nameFacet1.Value = "255";
 20             XmlSchemaMinLengthFacet _nameFacet2 = new XmlSchemaMinLengthFacet();
 21             _nameFacet2.Value = "3";
 22             _nameTypeRes.Facets.Add(_nameFacet1);
 23             _nameTypeRes.Facets.Add(_nameFacet2);
 24
 25             _nameType.Content = _nameTypeRes;
 26
 27
 28             //定义简单类型 PhoneSimpleType
 29             XmlSchemaSimpleType _phoneType = new XmlSchemaSimpleType();
 30
 31             XmlSchemaSimpleTypeRestriction _phoneTypeRes = new XmlSchemaSimpleTypeRestriction();
 32             _phoneTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
 33             XmlSchemaMaxLengthFacet _phoneFacet1 = new XmlSchemaMaxLengthFacet();
 34             _phoneFacet1.Value = "25";
 35             _phoneTypeRes.Facets.Add(_phoneFacet1);
 36
 37             _phoneType.Content = _phoneTypeRes;
 38
 39
 40
 41             // 定义简单类型 NotesSimpleType
 42             XmlSchemaSimpleType _notesType = new XmlSchemaSimpleType();
 43
 44             XmlSchemaSimpleTypeRestriction _notesTypeRes = new XmlSchemaSimpleTypeRestriction();
 45             _notesTypeRes.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");
 46
 47             XmlSchemaMaxLengthFacet _notesFacet1 = new XmlSchemaMaxLengthFacet();
 48             _notesFacet1.Value = "500";
 49
 50             _notesTypeRes.Facets.Add(_notesFacet1);
 51             _notesType.Content = _notesTypeRes;
 52
 53
 54             // 定义CustomerType复杂类型
 55             XmlSchemaComplexType _customerType = new XmlSchemaComplexType();
 56
 57             XmlSchemaSequence _sequence = new XmlSchemaSequence();
 58
 59             XmlSchemaElement _firstName = new XmlSchemaElement();
 60             _firstName.Name = "firstName";
 61             _firstName.SchemaType = _nameType;
 62
 63             XmlSchemaElement _lastName = new XmlSchemaElement();
 64             _lastName.Name = "lastName";
 65             _lastName.SchemaType = _nameType;
 66
 67             XmlSchemaElement _homePhone = new XmlSchemaElement();
 68             _homePhone.Name = "homePhone";
 69             _homePhone.SchemaType = _phoneType;
 70
 71             XmlSchemaElement _notes = new XmlSchemaElement();
 72             _notes.Name = "notes";
 73             _notes.SchemaType = _notesType;
 74
 75             _sequence.Items.Add(_firstName);
 76             _sequence.Items.Add(_lastName);
 77             _sequence.Items.Add(_homePhone);
 78             _sequence.Items.Add(_notes);
 79
 80             _customerType.Particle = _sequence;
 81
 82
 83             // 定义属性customerId
 84             XmlSchemaAttribute _customerId = new XmlSchemaAttribute();
 85             _customerId.Name = "customerId";
 86             _customerId.SchemaTypeName = new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema");
 87             _customerId.Use = XmlSchemaUse.Required;
 88             _customerType.Attributes.Add(_customerId);
 89
 90             // 定义 CustomersType 复杂类型
 91             XmlSchemaComplexType _customersType = new XmlSchemaComplexType();
 92             XmlSchemaSequence _sq = new XmlSchemaSequence();
 93             XmlSchemaElement _customer = new XmlSchemaElement();
 94             _customer.Name = "customer";
 95             _customer.SchemaType = _customerType;
 96             _customer.MinOccurs = 0;
 97             _customer.MaxOccursString = "unbounded";
 98             _sq.Items.Add(_customer);
 99             _customersType.Particle = _sq;
100
101
102
103             // 定义 customers 元素
104             XmlSchemaElement _customers = new XmlSchemaElement();
105             _customers.Name = "customers";
106             _customers.SchemaType = _customersType;
107
108
109             // 把 customers 元素, 添加到模式_schema下
110             _schema.Items.Add(_customers);
111
112
113             try
114             {
115                 XmlSchemaSet _set = new XmlSchemaSet();
116                 _set.Add(_schema);
117                 _set.Compile();
118             }
119             catch (Exception ex)
120             {
121                 Console.WriteLine("模式编译失败:" + ex.Message);
122             }
123
124
125             XmlTextWriter _write = new XmlTextWriter(getProjectPath() + "files\\customers.xsd", System.Text.Encoding.UTF8);
126             _schema.Write(_write);
127             _write.Close();
128
129         }
130
131
132
133         /// <summary>
134         /// 通过 XmlReader 在加载XML文档时同时加载XSD进行校验
135         /// </summary>
136         private static void BooksValidationByXmlReader()
137         {
138             XmlSchemaSet schemaSet = new XmlSchemaSet();
139             schemaSet.Add("urn:bookstore-schema", booksXsdPath);
140
141             XmlReaderSettings settings = new XmlReaderSettings();
142             settings.ValidationType = ValidationType.Schema;
143             settings.Schemas = schemaSet;
144             settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
145
146             // 在加载XML文档时同时,加载XSD,进行校验
147             XmlReader reader = XmlReader.Create(booksXmlPath, settings);
148
149             while (reader.Read()) ;
150             /*
151              * Validation Error: The element ‘book‘ in namespace ‘urn:bookstore-schema‘
152              * has invalid child element ‘author‘ in namespace ‘urn:bookstore-schema‘.
153              *
154              * List of possible elements expected: ‘title‘ in namespace ‘urn:bookstore-schema‘.
155              *
156              * Validation Error: The element ‘author‘ in namespace ‘urn:bookstore-schema‘
157              * has invalid child element‘name‘ in namespace ‘urn:bookstore-schema‘.
158              *
159              * List of possible elements expected: ‘first-name‘ in namespace ‘urn:bookstore-schema‘.
160              *
161              * */
162         }
163
164         /// <summary>
165         /// 通过XmlDocument类的 Validate() 方法,验证XML数据是否符合指定的XSD模式文件
166         /// </summary>
167         private static void BooksValidationByXmlDocument()
168         {
169             XmlDocument doc = new XmlDocument();
170
171             /*
172              * doc.LoadXml() 从指定的xml string 字符串中解析XML DOM
173              * */
174             doc.Load(booksXmlPath);
175             doc.Schemas.Add("urn:bookstore-schema", booksXsdPath);
176             doc.Validate(ValidationCallBack);
177
178         }
179
180         /// <summary>
181         /// 使用XPathDocument遍历XML文档
182         /// </summary>
183         private static void XPathNavigatorTravel()
184         {
185             XPathDocument _doc = new XPathDocument(getProjectPath() + "files\\Customers.xml");
186             XPathNavigator _navigator = _doc.CreateNavigator();
187
188             _navigator.MoveToRoot(); // 移到文档的根(文档根下有: XML声明, XML处理指令, XML根元素customers )
189             _navigator.MoveToFirstChild(); // 移到XML根元素customers
190
191             if (_navigator.HasChildren)
192             {
193                 _navigator.MoveToFirstChild(); // 移到根元素customers的customer子元素
194
195                 do
196                 {
197                     string _id = _navigator.GetAttribute("customerid", "http://asn.test.xsd/customers");
198                     Console.WriteLine("Customer ID: " + _id);
199
200                     _navigator.MoveToFirstChild();  // 移动到customer元素的firstname子元素
201
202                     do
203                     {
204                         Console.WriteLine("  " + _navigator.Name + ": " + _navigator.Value);
205                     } while(_navigator.MoveToNext());
206
207                     _navigator.MoveToParent();
208                 }
209                 while (_navigator.MoveToNext());
210             }
211
212         }
213
214         /// <summary>
215         /// 使用 XPathNavigator 类的 Select()方法, 选择XML文档节点
216         /// </summary>
217         private static void XPathNavigatorSelect()
218         {
219             XPathDocument _doc = new XPathDocument(getProjectPath() + "files\\Customers.xml");
220             XPathNavigator _navigator = _doc.CreateNavigator();
221             XmlNamespaceManager _manager = new XmlNamespaceManager(_navigator.NameTable);
222             _manager.AddNamespace("cust", "http://asn.test.xsd/customers");
223
224             XPathNodeIterator _iterator = _navigator.Select("//cust:customer[@customerid=2]", _manager);
225
226             Console.WriteLine("选中的节点个数:" + _iterator.Count);
227
228             StringBuilder resultsb = new StringBuilder();
229             int number = 1;
230             if (_iterator.Count > 0)
231             {
232                 while (_iterator.MoveNext())
233                 {
234                     resultsb.Append("第" + (number++) + "个customer节点:" + _iterator.Current.OuterXml);
235                 }
236             }
237             else
238             {
239                 resultsb.Append("无匹配的节点");
240             }
241
242             Console.WriteLine(resultsb.ToString());
243
244         }
245
246
247         static void Main(string[] args)
248         {
249
250             //BooksValidationByXmlDocument();
251
252             //GenCustomerXSD();
253
254             XPathNavigatorSelect();
255
256         }
257
258
259         /// <summary>
260         /// 校验出错时的回调方法
261         /// </summary>
262         /// <param name="sender"></param>
263         /// <param name="e"></param>
264         public static void ValidationCallBack(object sender, ValidationEventArgs e)
265         {
266             Console.WriteLine("Validation Error: {0}", e.Message);
267         }
268
269         public static string getProjectPath()
270         {
271             string basePath = AppDomain.CurrentDomain.BaseDirectory;   //  \\XmlTest\\bin\\Debug\\
272             string projectPath = basePath.Substring(0, basePath.IndexOf("bin"));
273             return projectPath;
274         }
275     }
时间: 2024-10-16 13:18:33

C# 操作XML学习笔记的相关文章

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

Delphi 对XML的支持---TXMLDocument类 Delphi7 支持对XML文档的操作,可以通过TXMLDocument类来实现对XML文档的读写.可以利用TXMLDocument把XML文档读到内存中,从而可以进行编辑.保存操作.TXMLDocument类是通过DOM(文档对象模型)接口来访问XML文档中的各个元素的.对于DOM接口的实现有多种方式,Delphi支持的方式有:1)微软的MSXML SDK,这种方式是通过COM对象来实现:2) Apache 的Xerces的实现方式

XML学习笔记(五):使用 jdom和dom4j 解析XML

XML解析的详细分析与jaxp解析XML详见:XML学习笔记(四):使用 DOM和SAX 解析XML 一.JDom 1.创建XML文件: 1)Document类即代表整个XML文档,把生成的 Document 利用 XMLOutputter 类输出即可. 2)映射关系:元素:Element:属性:Attribute:注解:Comment:文本信息:Text: 3)注意:addContent()是追加,setContent()会覆盖. /** * 创建XML * * @throws IOExcep

xml学习笔记(1)

xml 学习笔记 XML : W3C 提供的可拓展的HTMl标签 作用 : 存储,配置 数据存储在XMl中,写好XML文件后要用程序去读取其中的数据,而读取程序的过程叫做解析. xml 的解析方式分为两种: dom (Document Objecct Model 文档对象模型) W3C组织推荐的解析模式 Sax (Simple API for Xml )是xml社区事实上的标准 ,几乎所有的XML解析器都支持它 XML 解析器: Crimson(sun ) Xerces(IBM) Aelfred

xml学习笔记 6.XQuery

XQuery xml query 是一种专门用于xml半结构化数据的查询语言,是W3C的推荐的标准语言. XQuery是有一些SQL专家制定的,基本语法与sql语句非常相似.比xslt更加简单. FLOWR语句与select语句相对应,完成对xml数据的查询,筛选和排序.FLOWR是指FOR,LET,WHERE,ORDERBY,RETURN五种语句.其中可以使用XPATH路径表达式以及xpath中的内置函数,各种自定义的函数,和命名空间. for子句: for $b in doc("bib-de

C#操作XML学习(一)

一.简单介绍 using System.Xml; //初始化一个xml实例 XmlDocument xml=new XmlDocument(); //导入指定xml文件 xml.Load(path); xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); //指定一个节点 XmlNode root=xml.SelectSingleNode("/root"); //获取节点下所有直接

XML学习笔记之:XSLT &lt;xsl:variable&gt; 元素

声明:该笔记引自W3School! 1.<xsl:variable> 元素用于声明局部或全局的变量. 2.可以通过 <xsl:variable> 元素的内容或通过 select 属性,向变量添加值! 3.一旦设置了变量的值,就无法改变或修改该值! <xsl:variable name="name" select="expression"> <!-- Content:template --> </xsl:varia

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

Flas-SQLAchemy数据库操作使用学习笔记 1.为你的Flask应用加载Flask-SqlAlchemy扩展 Code example: 1.1from flask import Flask f rom flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(ap

XML From Action Script[AS中的XML学习笔记]

XML From Action Script XML 是 eXtensible Markup Language (可扩展标记语言)的缩写. E4X ECMAScript for XML 规范定义了一组用于处理 XML 数据的类和功能.这些类和功能统称为 E4X. ActionScript 3.0 包含 以下 E4X 类:XML. XMLList. QName 和 Namespace. E4X 包含了一些直观运算符(如点 (.) 和属性标识符 (@) 运算符),用于访问 XML 中的属性 (pro

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

1. 介绍(四种方式的比较这部分转载自:http://www.blogjava.net/xcp/archive/2010/02/12/312617.html) 1)DOM(JAXP Crimson解析器)         DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找特定信息.分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作.由于它是基于信息层次的,因而DOM被认为是基于树或基于对象