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     }

 

posted @ 2014-10-20 13:37  asnjudy  阅读(314)  评论(0编辑  收藏  举报