全面分析VB.NET XmlWriter
VB.NET有很多值得學習的地方,這里我們主要介紹VB.NET XmlWriter,檢索屬性數(shù)據(jù)等方面,下面我們就來看看吧。
檢索屬性數(shù)據(jù)
AttributeCountry屬性確定屬性個數(shù)。GetAttribute()方法按照名稱或索引來獲取屬性,如果要一次迭代一個屬性就可以使用MoveToFirstAttribute()和MoveToNextAttribute()方法。
如下代碼:
- richTextBox1.Clear();
- XmlReader tr = XmlReader.Create("book.xml");
- while (tr.Read()){
- if (tr.NodeType == XmlNodeType.Element){
- for (int i = 0; i < tr.AttributeCount; i++){
- richTextBox1.AppendText(tr.GetAttribute(i)+"\r\n");
- }
- }
- }
使用XmlReader類進行驗證
有時不但要知道文檔的格式是規(guī)范的,還是確定文檔是有效的。
XmlReader可以使用XmlReaderSettings,根據(jù)XSD模式驗證XML。XSD模式添加到XMLSchemaSet中,通過Schema屬性可以訪問XMLSchemaSet。XsdValidate屬性還必須設(shè)置為ture,這個屬性默認為flase. VB.NET XmlWriter類可以把Xml寫入一個流、文件、StringBuilder、TextWriter或另一個XmlWriter對象中。與VB.NET XmlWriterr一樣,XmlWriter類以只向前、未緩存的方式 進行寫入。
使用XmlWirterSettings對旬進行是否縮進文本、縮進量等配置。
如下代碼:
- XmlWriterSettings settings = new XmlWriterSettings();
- settings.Indent = true; //是否縮進
- settings.NewLineOnAttributes = true;//把每個屬性寫在一行,這樣做可以更容易讀取
- XMLXmlWriter writer = XmlWriter.Create("booknew.xml",settings);
- writer.WriteStartDocument();
- writer.WriteStartElement("book");
- writer.WriteAttributeString("genre","Mystery");
- writer.WriteAttributeString("publicationdate","2001");
- writer.WriteAttributeString("ISBN","123456489");
- writer.WriteElementString("title","Case of the Money");
- writer.WriteStartElement("author");
- writer.WriteElementString("name","Cookie Monster");
- writer.WriteEndElement();
- writer.WriteElementString("price","9.99");
- writer.WriteEndDocument();
- writer.Flush();
- writer.Close();
1.使用XmlWriterSettings實例對象進行生成的XML的設(shè)置。
2.使用Create(),返回一個VB.NET XmlWriter對象,其中Create(),第一個參數(shù)為Xml的名字,第二個參數(shù)為XmlWriterSettings實例對象。
3.使用WriterStartDocument()中文檔聲明,開始寫入數(shù)據(jù),以WriteEndDocument()結(jié)束。注間控制元素的嵌套,注注意WriterStartElement()和WriterEndElement()的調(diào)用與位置。
4.還有一些專用的寫入方法。WriteCData()可以輸出一個CData部分(),WriterComment()以正確的XML格式寫入注釋。WriteChae()寫入字符緩沖區(qū)的內(nèi)容。