发布日期: 2016年7月 程序集: System.Xml(位于 System.Xml.dll) System.Object System.Xml.XmlNode System.Xml.XmlDocument System.Configuration.ConfigXmlDocument System.Xml.XmlDataDocument Public Class XmlDocument Inherits XmlNode
<?xml version="1.0" encoding="utf-8"?> <books xmlns="http://www./books"> <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28"> <title>Pride And Prejudice</title> <price>24.95</price> </book> <book genre="novel" ISBN="1-861002-30-1" publicationdate="1985-01-01"> <title>The Handmaid's Tale</title> <price>29.95</price> </book> <book genre="novel" ISBN="1-861001-45-3" publicationdate="1811-01-01"> <title>Sense and Sensibility</title> <price>19.95</price> </book> </books> Imports System Imports System.Management Public Class Sample Public Overloads Shared Function _ Main(ByVal args() As String) As Integer ' Get the WMI class path Dim p As ManagementPath = _ New ManagementPath( _ "\\ComputerName\root" & _ "\cimv2:Win32_LogicalDisk.DeviceID=""C:""") Console.WriteLine("IsClass: " & _ p.IsClass) ' Should be False (because it is an instance) Console.WriteLine("IsInstance: " & _ p.IsInstance) ' Should be True Console.WriteLine("ClassName: " & _ p.ClassName) ' Should be "Win32_LogicalDisk" Console.WriteLine("NamespacePath: " & _ p.NamespacePath) ' Should be "ComputerName\cimv2" Console.WriteLine("Server: " & _ p.Server) ' Should be "ComputerName" Console.WriteLine("Path: " & _ p.Path) ' Should be "ComputerName\root\cimv2: ' Win32_LogicalDisk.DeviceId="C:"" Console.WriteLine("RelativePath: " & _ p.RelativePath) ' Should be "Win32_LogicalDisk.DeviceID="C:"" End Function End Class <?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www./2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www./books"> <xs:element name="books"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="book"> <xs:complexType> <xs:sequence> <xs:element name="title" type="xs:string" /> <xs:element name="price" type="xs:decimal" /> </xs:sequence> <xs:attribute name="genre" type="xs:string" use="required" /> <xs:attribute name="ISBN" type="xs:string" use="required" /> <xs:attribute name="publicationdate" type="xs:date" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> '************************************************************************************ ' ' Associate the schema with XML. Then, load the XML and validate it against ' the schema. ' '************************************************************************************ Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument Dim reader As XmlReader Dim settings As XmlReaderSettings = New XmlReaderSettings ' Helper method to retrieve schema. Dim schema As XmlSchema = getSchema(generateSchema) If (schema Is Nothing) Then Return Nothing End If settings.Schemas.Add(schema) AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings) settings.ValidationType = ValidationType.Schema Try reader = XmlReader.Create("booksData.xml", settings) Catch ex As System.IO.FileNotFoundException If generateXML Then Dim xml As String = generateXMLString() Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml) Dim stream As MemoryStream = New MemoryStream(byteArray) reader = XmlReader.Create(stream, settings) Else Return Nothing End If End Try Dim doc As XmlDocument = New XmlDocument doc.PreserveWhitespace = True doc.Load(reader) reader.Close() Return doc End Function '************************************************************************************ ' ' Helper method that generates an XML Schema. ' '************************************************************************************ Private Function generateXMLSchema() As String Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _ "<xs:schema attributeFormDefault=""unqualified"" " & _ "elementFormDefault=""qualified"" targetNamespace=""http://www./books"" " & _ "xmlns:xs=""http://www./2001/XMLSchema""> " & _ "<xs:element name=""books""> " & _ "<xs:complexType> " & _ "<xs:sequence> " & _ "<xs:element maxOccurs=""unbounded"" name=""book""> " & _ "<xs:complexType> " & _ "<xs:sequence> " & _ "<xs:element name=""title"" type=""xs:string"" /> " & _ "<xs:element name=""price"" type=""xs:decimal"" /> " & _ "</xs:sequence> " & _ "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _ "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _ "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _ "</xs:complexType> " & _ "</xs:element> " & _ "</xs:sequence> " & _ "</xs:complexType> " & _ "</xs:element> " & _ "</xs:schema> " Return generatedXmlSchema End Function '************************************************************************************ ' ' Helper method that gets a schema ' '************************************************************************************ Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema Dim xs As XmlSchemaSet = New XmlSchemaSet Dim schema As XmlSchema Try schema = xs.Add("http://www./books", "booksData.xsd") Catch ex As System.IO.FileNotFoundException If generateSchema Then Dim xmlSchemaString As String = generateXMLSchema() Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString) Dim stream As MemoryStream = New MemoryStream(byteArray) Dim reader As XmlReader = XmlReader.Create(stream) schema = xs.Add("http://www./books", reader) Else Return Nothing End If End Try Return schema End Function '************************************************************************************ ' ' Helper method to validate the XML against the schema. ' '************************************************************************************ Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument) If (doc.Schemas.Count = 0) Then ' Helper method to retrieve schema. Dim schema As XmlSchema = getSchema(generateSchema) doc.Schemas.Add(schema) End If ' Use an event handler to validate the XML node against the schema. doc.Validate(AddressOf settings_ValidationEventHandler) End Sub '************************************************************************************ ' ' Event handler that is raised when XML doesn't validate against the schema. ' '************************************************************************************ Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs) If (e.Severity = XmlSeverityType.Warning) Then System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message)) ElseIf (e.Severity = XmlSeverityType.Error) Then System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message)) Dim objectType As Type = sender.GetType End If End Sub Option Strict Option Explicit Imports System Imports System.IO Imports System.Xml Public Class Sample Public Shared Sub Main() 'Create the XmlDocument. Dim doc As New XmlDocument() doc.LoadXml("<?xml version='1.0' ?>" & _ "<book genre='novel' ISBN='1-861001-57-5'>" & _ "<title>Pride And Prejudice</title>" & _ "</book>") 'Display the document element. Console.WriteLine(doc.DocumentElement.OuterXml) End Sub 'Main End Class 'Sample Option Strict Option Explicit Imports System Imports System.IO Imports System.Xml Public Class Sample Public Shared Sub Main() Dim doc As New XmlDocument() doc.LoadXml("<book ISBN='1-861001-57-5'>" & _ "<title>Pride And Prejudice</title>" & _ "<price>19.95</price>" & _ "</book>") Dim root As XmlNode = doc.FirstChild 'Display the contents of the child nodes. If root.HasChildNodes Then Dim i As Integer For i = 0 To root.ChildNodes.Count - 1 Console.WriteLine(root.ChildNodes(i).InnerText) Next i End If End Sub 'Main End Class 'Sample Option Explicit Option Strict Imports System Imports System.IO Imports System.Xml Public Class Sample Public Shared Sub Main() Dim doc As New XmlDocument() doc.LoadXml("<book ISBN='1-861001-57-5'>" & _ "<title>Pride And Prejudice</title>" & _ "<price>19.95</price>" & _ "</book>") Dim root As XmlNode = doc.FirstChild Console.WriteLine("Display the price element...") Console.WriteLine(root.LastChild.OuterXml) End Sub 'Main End Class 'Sample Imports System Imports System.Xml Imports Microsoft.VisualBasic public class Sample public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.Load("books.xml") Dim currNode as XmlNode = doc.DocumentElement.FirstChild Console.WriteLine("First book...") Console.WriteLine(currNode.OuterXml) Dim nextNode as XmlNode = currNode.NextSibling Console.WriteLine(ControlChars.LF + "Second book...") Console.WriteLine(nextNode.OuterXml) end sub end class Imports System Imports System.Xml Imports Microsoft.VisualBasic public class Sample public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.Load("books.xml") Dim lastNode as XmlNode = doc.DocumentElement.LastChild Console.WriteLine("Last book...") Console.WriteLine(lastNode.OuterXml) Dim prevNode as XmlNode = lastNode.PreviousSibling Console.WriteLine(ControlChars.LF + "Previous book...") Console.WriteLine(prevNode.OuterXml) end sub end class Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable) nsmgr.AddNamespace("bk", "http://www./books") Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _ & (uniqueAttribute & "']")) Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr) Return xmlNode End Function Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode) Dim bookElement As XmlElement = CType(book, XmlElement) ' Get the attributes of a book. Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN") ISBN = attr.InnerXml attr = bookElement.GetAttributeNode("genre") genre = attr.InnerXml attr = bookElement.GetAttributeNode("publicationdate") publicationDate = attr.InnerXml ' Get the values of child elements of a book. title = bookElement("title").InnerText price = bookElement("price").InnerText End Sub Imports System Imports System.IO Imports System.Xml public class Sample public shared sub Main() 'Create the XmlDocument. Dim doc as XmlDocument = new XmlDocument() doc.Load("booksort.xml") Dim book as XmlNode Dim nodeList as XmlNodeList Dim root as XmlNode = doc.DocumentElement nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']") 'Change the price on the books. for each book in nodeList book.LastChild.InnerText="15.95" next Console.WriteLine("Display the modified XML document....") doc.Save(Console.Out) end sub end class Option Explicit Option Strict Imports System Imports System.IO Imports System.Xml Public Class Sample Public Shared Sub Main() 'Create the XmlDocument. Dim doc As New XmlDocument() doc.Load("books.xml") 'Display all the book titles. Dim elemList As XmlNodeList = doc.GetElementsByTagName("title") Dim i As Integer For i = 0 To elemList.Count - 1 Console.WriteLine(elemList(i).InnerXml) Next i End Sub 'Main End Class 'Sample Public Sub editBook(ByVal title As String, ByVal ISBN As String, ByVal publicationDate As String, ByVal genre As String, ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean, ByVal generateSchema As Boolean) Dim bookElement As XmlElement = CType(book, XmlElement) ' Get the attributes of a book. bookElement.SetAttribute("ISBN", ISBN) bookElement.SetAttribute("genre", genre) bookElement.SetAttribute("publicationdate", publicationDate) ' Get the values of child elements of a book. bookElement("title").InnerText = title bookElement("price").InnerText = price If validateNode Then validateXML(generateSchema, bookElement.OwnerDocument) End If End Sub Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement ' Create a new book element. Dim bookElement As XmlElement = doc.CreateElement("book", "http://www./books") ' Create attributes for book and append them to the book element. Dim attribute As XmlAttribute = doc.CreateAttribute("genre") attribute.Value = genre bookElement.Attributes.Append(attribute) attribute = doc.CreateAttribute("ISBN") attribute.Value = ISBN bookElement.Attributes.Append(attribute) attribute = doc.CreateAttribute("publicationdate") attribute.Value = misc bookElement.Attributes.Append(attribute) ' Create and append a child element for the title of the book. Dim titleElement As XmlElement = doc.CreateElement("title") titleElement.InnerText = title bookElement.AppendChild(titleElement) ' Introduce a newline character so that XML is nicely formatted. bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _ "\n " & titleElement.OuterXml & " " & ControlChars.NewLine + " ") ' Create and append a child element for the price of the book. Dim priceElement As XmlElement = doc.CreateElement("price") priceElement.InnerText = price bookElement.AppendChild(priceElement) ' Introduce a newline character so that XML is nicely formatted. bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml, (priceElement.OuterXml & " " & ControlChars.NewLine & " ")) Return bookElement End Function Public Sub deleteBook(ByVal book As XmlNode) Dim prevNode As XmlNode = book.PreviousSibling book.OwnerDocument.DocumentElement.RemoveChild(book) If ((prevNode.NodeType = XmlNodeType.Whitespace) _ OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode) End If End Sub '************************************************************************************ ' ' Summary: Move elements up in the XML. ' ' '************************************************************************************ Public Sub MoveElementUp(ByVal book As XmlNode) Dim previousNode As XmlNode = book.PreviousSibling While ((Not (previousNode) Is Nothing) _ AndAlso (previousNode.NodeType <> XmlNodeType.Element)) previousNode = previousNode.PreviousSibling End While If (Not (previousNode) Is Nothing) Then Dim newLineNode As XmlNode = book.NextSibling book.OwnerDocument.DocumentElement.RemoveChild(book) If ((newLineNode.NodeType = XmlNodeType.Whitespace) _ Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode) End If InsertBookElement(CType(book, XmlElement), Constants.positionAbove, previousNode, False, False) End If End Sub '************************************************************************************ ' ' Summary: Move elements down in the XML. ' ' '************************************************************************************ Public Sub MoveElementDown(ByVal book As XmlNode) ' Walk backwards until we find an element - ignore text nodes Dim NextNode As XmlNode = book.NextSibling While ((Not (NextNode) Is Nothing) _ AndAlso (NextNode.NodeType <> XmlNodeType.Element)) NextNode = NextNode.NextSibling End While If (Not (NextNode) Is Nothing) Then Dim newLineNode As XmlNode = book.PreviousSibling book.OwnerDocument.DocumentElement.RemoveChild(book) If ((newLineNode.NodeType = XmlNodeType.Whitespace) _ Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode) End If InsertBookElement(CType(book, XmlElement), Constants.positionBelow, NextNode, False, False) End If End Sub
|
|
来自: 龙门过客栈 > 《System.Xml》