May 13, 2021 vb.net
Extensable tag language (XML) is a tag language that is very similar to HTML or SGML.
This is recommended by the World Wide Web Alliance and can be used as an open standard.
. T
he System.Xml namespace in the Net framework contains classes for working with XML documents.
Here are some of the classes commonly used in the System.Xml namespace.
SN | Class | Describe |
---|---|---|
1 | XmlAttribute | Represents a property. The valid and default values of the property are defined in the document type definition (DTD) or pattern. |
2 | XmlCDataSection | Represents a CDATA section. |
3 | XmlCharacterData | Provides text processing methods that are used by several classes. |
4 | XMLCOMMENT | Represents the contents of an XML comment. |
5 | XmlConvert | Encode and decode XML names and provide a way to convert between the common language runtime type and the XML pattern definition language (XSD) type. When you convert a data type, the value returned is independent of the locale. |
6 | XmlDeclaration | Represents XML Claims Nodes . . . x ml version ='1.0'...? >。 |
7 | XmlDictionary | Implement an XML reader/writer implementation with a dictionary to optimize the Windows Communication Foundation (WCF). |
8 | XmlDictionaryReader | The Windows Communication Foundation (WCF) derives abstract classes from XmlReader for serialization and antiseration. |
9 | XmlDictionaryWriter | An abstract class that represents that Windows Communication Foundation (WCF) is derived from XmlWriter for serialization and counterserization. |
10 | XmlDocument | Represents an XML document. |
11 | XmlDocumentFragment | Represents lightweight objects that are useful for tree insertion. |
12 | XmlDocumentType | Represents a document type declaration. |
13 | XmlElement | Represents an element. |
14 | XmlEntity | Represents an entity declaration, such as E NTITY ... >。 |
15 | XmlEntityReference | Represents an entity reference node. |
16 | XmlException | Returns more information about the last exception. |
17 | XmlImplementation | Define the context of a set of XmlDocument objects. |
18 | XmlLinkedNode | Gets the node before or after this node. |
19 | XmlNode | Represents a single node in an XML document. |
20 | XmlNodeList | Represents an ordered collection of nodes. |
21 | XmlNodeReader | Represents a reader that provides fast, non-cached forwarding access to XML data in XmlNode. |
22 | XmlNotation | Represents a comment statement, such as the .lt;! N OTATION ... >。 |
23 | XmlParserContext | Provides all the context information that XmlReader needs to parse XML fragments. |
24 | XmlProcessingInstruction | Represents processing instructions, and XML is defined as retaining processor-specific information in the text of the document. |
25 | XmlQualifiedName | Represents an XML qualified name. |
26 | XmlReader | Represents a reader that provides fast, non-cached access to XML data only. |
27 | XmlReaderSettings | Specify a set of features to support on XmlReader objects created by the Creative method. |
28 | XmlResolver | Resolves external XML resources named after a unified resource identifier (URI). |
29 | XmlSecureResolver | Another implementation that helps protect XmlResolver by encapsulating the XmlResolver object and limiting the resources that the underlying XmlResolver has access to. |
30 | XmlSignificantWhitespace | Represents spaces between tags in the mixed content node or in the blank space within the range of xml:space.'preserve'. This is also known as a valid blank space. |
31 | XmlText | The text content that represents an element or property. |
32 | XmlTextReader | Represents a reader that provides fast, non-cached, forward-only access to XML data. |
33 | XmlTextWriter | Representing writers provides a fast, non-cache-only way to generate XML data streams or files that contain namespaces that conform to the W3C Extensable Markup Language (XML) 1.0 and XML. |
34 | XmlUrlResolver | Resolves external XML resources named after a unified resource identifier (URI). |
35 | XmlWhitespace | Represents white space in the contents of an element. |
36 | XmlWriter | Represents a writer that provides fast, non-cached, forward-only generation of streams or files containing XML data. |
37 | XmlWriterSettings | Specify a set of features to support on XmlWriter objects created by the XmlWriter.Create method. |
The two most basic and widely used APIs for XML data are the SAX and DOM interfaces.
XML's Simple API (SAX): Here you register a
callback for the event of interest and let the parser continue working on the document.
This is useful when the document is large or memory-limited, and it resolves files when they are read from disk, and the entire file is never stored in memory.
Document Object Model (DOM) API: This is recommended
by the World Wide Web Federation, where the entire file is read into memory and stored in a hierarchical (tree-based) form to represent all the characteristics of an XML document.
SAX obviously can't process information as quickly as the DOM when using large files.
On the other hand, using DOM can really kill your resources, especially if used for many small files.
SAX is read-only, and the DOM allows changes to XML files.
Since these two different APIs are literally complementary, there's no reason why you can't use them for two big projects.
For all the XML code examples, let's use a simple XML file .xml as input:
<?xml version="1.0"?> <collection shelf="New Arrivals"> <movie title="Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description> </movie> <movie title="Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description> </movie> <movie title="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection>
In the SAX model, XmlReader and XmlWriter classes are used to process XML data.
The XmlReader class is used to read XML data quickly, forward and non-cached only.
It reads XML documents or streams.
This example demonstrates reading XML data .xml file movies file.
Follow these steps:
Add the .xml files to the application's bin sdbug folder.
Import system.vb.Xml namespaces in the Form1 file.
Add a label to the form and change its text to Movies Galore.
Add three list boxes and three buttons to display the title, type, and description of the movie from the xml file.
Use the code editor window to add the following code.
Imports System.Xml Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ListBox1().Items.Clear() Dim xr As XmlReader = XmlReader.Create("movies.xml") Do While xr.Read() If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie" Then ListBox1.Items.Add(xr.GetAttribute(0)) End If Loop End Sub Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click ListBox2().Items.Clear() Dim xr As XmlReader = XmlReader.Create("movies.xml") Do While xr.Read() If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type" Then ListBox2.Items.Add(xr.ReadElementString) Else xr.Read() End If Loop End Sub Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click ListBox3().Items.Clear() Dim xr As XmlReader = XmlReader.Create("movies.xml") Do While xr.Read() If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "description" Then ListBox3.Items.Add(xr.ReadElementString) Else xr.Read() End If Loop End Sub End Class
Use the Start button on the Microsoft Visual Studio toolbar to execute and run the code above. C licking the button displays the title, type, and description of the movie in the file.
The XmlWriter class is used to write XML data to streams, files, or TextWriter objects. I t also works in a forward-only, non-cached manner.
Let's create an XML file by adding some data at runtime. F ollow these steps:
Add WebBrowser controls and button controls to the form.
Change the Text property of the button to show the author file.
Add the following code to the code editor.
Imports System.Xml Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim xws As XmlWriterSettings = New XmlWriterSettings() xws.Indent = True xws.NewLineOnAttributes = True Dim xw As XmlWriter = XmlWriter.Create("authors.xml", xws) xw.WriteStartDocument() xw.WriteStartElement("Authors") xw.WriteStartElement("author") xw.WriteAttributeString("code", "1") xw.WriteElementString("fname", "Zara") xw.WriteElementString("lname", "Ali") xw.WriteEndElement() xw.WriteStartElement("author") xw.WriteAttributeString("code", "2") xw.WriteElementString("fname", "Priya") xw.WriteElementString("lname", "Sharma") xw.WriteEndElement() xw.WriteStartElement("author") xw.WriteAttributeString("code", "3") xw.WriteElementString("fname", "Anshuman") xw.WriteElementString("lname", "Mohan") xw.WriteEndElement() xw.WriteStartElement("author") xw.WriteAttributeString("code", "4") xw.WriteElementString("fname", "Bibhuti") xw.WriteElementString("lname", "Banerjee") xw.WriteEndElement() xw.WriteStartElement("author") xw.WriteAttributeString("code", "5") xw.WriteElementString("fname", "Riyan") xw.WriteElementString("lname", "Sengupta") xw.WriteEndElement() xw.WriteEndElement() xw.WriteEndDocument() xw.Flush() xw.Close() WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory + "authors.xml") End Sub End Class
Use the Start button on the Microsoft Visual Studio toolbar to execute and run the code above. C licking show author files will display the newly created autos file on .xml browser.
Depending on the document object model (DOM), the XML document consists of nodes and node properties. T he XmlDocument class is the XML DOM parser used to implement the .Net framework. It also allows you to modify existing XML documents by inserting, deleting, or updating data in the document.
Here are some common methods for the XmlDocument class:
SN | Method name and description |
---|---|
1 |
AppendChild
Add the specified node to the end of the list of child nodes for this node. |
2 |
CreateAttribute(String) Create XmlAttribute with the specified name. |
3 |
CreateComment Create an XmlComment that contains the specified data. |
4 |
CreateDefaultAttribute Create the default property with the specified prefix, local name, and namespace URI. |
5 |
CreateElement(String) Create an element with the specified name. |
6 |
CreateNode(String, String, String) Create XmlNode with the specified node type, Name and NamespaceURI. |
7 |
CreateNode(XmlNodeType, String, String) Create XmlNode with the specified XmlNodeType, Name, and NamespaceURI. |
8 |
CreateNode(XmlNodeType, String, String, String) Create XmlNode With specified XmlNodeType, Prefix, Name, and NamespaceURI. |
9 |
CreateProcessingInstruction Create an XmlProcessingInstruction with a specified name and data. |
10 |
CreateSignificantWhitespace Create an XmlSignificant Whitespace node. |
11 |
createTextNode Create an XMLTEXT with the specified text. |
12 |
CreateWhitespace Create an XmlWhitespace node. |
13 |
CreateXmlDeclaration Create an XmlDeclaration node with a specified value. |
14 |
GetElementById Gets XmlElement with the specified ID. |
15 |
GetElementsByTagName(String) Returns an XmlNodeList that contains a list of all descendant elements that match the specified name. |
16 |
GetElementsByTagName(String, String)
Returns an XmlNodeList that contains a list of all descendant elements that match the specified name. |
17 |
InsertAfter Insert the specified node immediately after the specified reference node. |
18 |
InsertBefore Insert the specified node before the specified reference node. |
19 |
Load(Stream) Load the XML document from the specified stream. |
20 |
Load(String) Load XML documents from the specified TextReader. |
21 |
Load(TextReader) Load XML documents from the specified TextReader. |
22 |
Load(XmlReader) Load the XML document from the specified XmlReader. |
23 |
LoadXml Load the XML document from the specified string. |
24 |
PrependChild Add the specified node to the beginning of the list of child nodes for this node. |
25 |
ReadNode Create an XmlNode object based on the information in XmlReader. T he reader must be on a node or property. |
26 |
RemoveAll Delete all child nodes and/or properties of the current node. |
27 |
RemoveChild Delete the specified child node. |
28 |
ReplaceChild Replace the child node oldChild with the newChild node. |
29 |
Save(Stream) Save the XML document to the specified stream. |
30 |
Save(String) Save the XML document to the specified file. |
31 |
Save(TextWriter) Save the XML document to the specified TextWriter. |
32 |
Save(XmlWriter) Save the XML document to the specified XmlWriter. |
In this example, let's insert some new nodes .xml the xml document auss, and then display the names of all the authors in the list box.
Follow these steps:
Add the .xml file to the application's bin/Debug folder (where you should be if you've tried the last example)
Import the System.Xml namespace
Add a list box and button control to the form and set the text property of the button control to Show Author.
Use the code editor to add the following code.
Imports System.Xml Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Set the caption bar text of the form. Me.Text = "tutorialspoint.com" End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ListBox1.Items.Clear() Dim xd As XmlDocument = New XmlDocument() xd.Load("authors.xml") Dim newAuthor As XmlElement = xd.CreateElement("author") newAuthor.SetAttribute("code", "6") Dim fn As XmlElement = xd.CreateElement("fname") fn.InnerText = "Bikram" newAuthor.AppendChild(fn) Dim ln As XmlElement = xd.CreateElement("lname") ln.InnerText = "Seth" newAuthor.AppendChild(ln) xd.DocumentElement.AppendChild(newAuthor) Dim tr As XmlTextWriter = New XmlTextWriter("movies.xml", Nothing) tr.Formatting = Formatting.Indented xd.WriteContentTo(tr) tr.Close() Dim nl As XmlNodeList = xd.GetElementsByTagName("fname") For Each node As XmlNode In nl ListBox1.Items.Add(node.InnerText) Next node End Sub End Class
Use the Start button on the Microsoft Visual Studio toolbar to execute and run the code above. C licking the Show Authors button will display the names of all authors, including those we added at runtime.