How to read XML from a URL
This example illustrates how to use the xmltextreader class to read XML from a URL.
Note: This example shows how to continue reading the XML topic from a file.
|
[Running example] | [View Source Code] |
Xmltextreader has different constructors to specify the location of XML data. This example loads xmltextreader: http: // localhost/Quickstart/howto/samples/XML/xmlreadfromurl/Vb/books from one of the URLs in the following languages. XML or http: // localhost/Quickstart/howto/samples/XML/xmlreadfromurl/CS/books. XML. The following sample code constructs an xmltextreader.
String URLString = "http://localhost/quickstart/howto/samples/Xml/XmlReadFromUrl/vb/books.xml"; // Load the XmlTextReader from the URL myXmlURLreader = new XmlTextReader (URLString); private const URLString as String = "http://localhost/quickstart/howto/samples/Xml/XmlReadFromUrl/vb/books.xml" ' Load the XmlTextReader from the URL myXmlURLreader = new XmlTextReader (URLString) |
C # |
VB |
|
After loading, the sample code calls the formatxml function. In this function, xmltextreader uses the read method to move XML data and read data in order to obtain the next node. If no node exists, this function returns false. For more information about the operating principles of the read method, see how to read XML from a file
while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: Format (reader, "XmlDeclaration"); declarationCount++; break; case XmlNodeType.ProcessingInstruction: Format (reader, "ProcessingInstruction"); piCount++; break; case XmlNodeType.DocumentType: Format (reader, "DocumentType"); docCount++; break; case XmlNodeType.Comment: Format (reader, "Comment"); commentCount++; break; case XmlNodeType.Element: Format (reader, "Element"); elementCount++; if (reader.HasAttributes) attributeCount += reader.AttributeCount; break; case XmlNodeType.Text: Format (reader, "Text"); textCount++; break; case XmlNodeType.Whitespace: whitespaceCount++; break; } } While reader.Read() Select (reader.NodeType) case XmlNodeType.XmlDeclaration: Format (reader, "XmlDeclaration") declarationCount += 1 case XmlNodeType.ProcessingInstruction: Format (reader, "ProcessingInstruction") piCount += 1 case XmlNodeType.DocumentType: Format (reader, "DocumentType") docCount += 1 case XmlNodeType.Comment: Format (reader, "Comment") commentCount += 1 case XmlNodeType.Element: Format (reader, "Element") elementCount += 1 if (reader.HasAttributes) attributeCount += reader.AttributeCount end if case XmlNodeType.Text: Format (reader, "Text") textCount += 1 case XmlNodeType.Whitespace: whitespaceCount += 1 End Select End While |
C # |
VB |
|
Summary
- Xmltextreader provides constructors to read XML from strings, file names, streams, or textreader that represent URLs.
- You can use the movetonextattribute method to access attribute nodes. This method allows you to determine the attributes of attribute nodes.