欢迎光临
我们一直在努力

建站超值云服务器,限时71元/月

how to: read xml data from a stream
this article discusses a beta release of a microsoft product. the information in this article is provided as-is and is subject to change without notice.

no formal product support is available from microsoft for this beta product. for information about obtaining support for a beta release, please see the documentation included with the beta product files, or check the web location from which you downloaded the release.
——————————————————————————–
the information in this article applies to:

microsoft .net development platform (ndp) beta 2

——————————————————————————–

in this task
summary
requirements
how to read xml data from a stream
references

summary
this article demonstrates how to use the xmltextreader class to read extensible markup language (xml) from a stream. the stream can come from a variety of sources, such as a byte stream from a server, a file, or a textreader class.

back to the top

requirements
the following list outlines the recommended hardware, software, network infrastructure, and service packs that you will need:
microsoft windows 2000 professional, windows 2000 server, windows 2000 advanced server, or windows nt 4.0 server
microsoft visual studio .net
this article assumes that you are familiar with the following topics:
xml terminology
creating and reading xml
how to read xml data from a stream
open visual studio .net.

create a new microsoft visual basic (vb) or microsoft visual c# console application.

note : the following steps provide a detailed description of how to build the application. you can also go directly to step 10, where completed code is provided.

make sure that the project contains a reference to the system.xml and system.io namespace.

use the imports statement on the xml namespace so that you are not required to qualify xmltextreader declarations in that namespace later in your code. you must use the imports statement prior to any other declarations as follows:

visual basic .net code
imports system.xml
imports system.io
visual c# code
using system.xml;
using system.io;
create or retrieve the xml stream. a stream is an abstract representation of an input or output device that is the source of, or destination for, data (in this case, xml data). you can write to and read from a stream, which is best visualized as a flow of bytes.

streams are used to provide independence from the device and therefore require no program changes if, for example, the source of a stream changes. there are a few different ways to create a stream for the xmltextreader class. select one of the following code samples to add to the main procedure of the default module:

code sample that uses the stringreader object:

the stringreader object reads characters from strings and takes in a string value during construction.

visual basic .net code
dim stream as system.io.stringreader
stream = new stringreader("<?xml version=1.0?>" & _
"<!– this file is a book store inventory. –>" & _
"<bookstore>" & _
" <book genre=""autobiography"" isbn=""1-861003-11-0"">" & _
"   <title>the autobiography of benjamin franklin</title>" & _
"   <author>" & _
"       <first-name>benjamin</first-name>" & _
"       <last-name>franklin</last-name>" & _
"   </author>" & _
"   <price>8.99</price>" & _
" </book>" & _
"</bookstore>")
c# code
stringreader stream;
stream = new stringreader("<?xml version=1.0?>" +
    "<!– this file represents a fragment of a book store inventory database. –>" +
    "<bookstore>" +
    " <book genre=\"autobiography\" publicationdate=\"1981\" isbn=\"1-861003-11-0\">" +
    "   <title>the autobiography of benjamin franklin</title>" +
    "   <author>" +
    "       <first-name>benjamin</first-name>" +
    "       <last-name>franklin</last-name>" +
    "   </author>" +
    "   <price>8.99</price>" +
    " </book>" +
    " <book genre=\"novel\" publicationdate=\"1967\" isbn=\"0-201-63361-2\">" +
    "   <title>the confidence man</title>" +
    "   <author>" +
    "       <first-name>herman</first-name>" +
    "       <last-name>melville</last-name>" +
    "   </author>" +
    "   <price>11.99</price>" +
    " </book>" +
    "  <book genre=\"philosophy\" publicationdate=\"1991\" isbn=\"1-861001-57-6\">" +
    "   <title>the gorgias</title>" +
    "   <author>" +
    "       <name>plato</name>" +
    "   </author>" +
    "   <price>9.99</price>" +
    " </book>" +
    "</bookstore>");
code sample that uses the streamreader object:

the streamreader object is used to read characters from files. it reads in the file name to be read during construction:

visual basic .net code
dim stream as system.io.streamreader
loads the xml data in the file books.xml in a new stream.
stream = new streamreader ("books.xml")
c# code
system.io.streamreader stream = new system.io.streamreader ("books.xml");
note that the books.xml file is used here. you can create your own books.xml file. a sample books.xml file is also shipped with visual studio .net and the .net framework sdk.

construct an xmltextreader class with the stream. typically, xmltextreader is used if you need to access the xml as raw data without the overhead of a document object model (dom); therefore, xmltextreader provides a faster mechanism for reading xml. xmltextreader has different constructors to specify the location of the xml data. the following code loads xmltextreader from a stream:

visual basic .net code
dim reader as xmltextreader = new xmltextreader (stream)
c# code
xmltextreader reader = null;    
reader = new xmltextreader (stream);
read through the xml. once loaded, xmltextreader performs sequential reads to move across the xml data and uses the read method to get the next record. it returns false if there are no more records.

visual basic .net code
do while (reader.read())
     do some work here on the data.
    console.writeline(reader.name)
loop

reading of the xml file has finished.
console.readline() pause
c# code
while (reader.read())
{
    // do some work here on the data.
    …
}

while (reader.read())
{
    // do some work here on the data.
    console.writeline(reader.name);
}
console.readline();
inspect the nodes. to process the xml data, each record has a node type, which can be determined from the nodetype property. the name and value properties return the node name (the element and attribute names) and the node value (the node text) of the current node (or record). the nodetype enumeration determines the node type. the following example displays the name of the elements and the document type. note that this example ignores element attributes.

visual basic .net code
do while (reader.read())
select case reader.nodetype
case xmlnodetype.element display beginning of element.
console.write("<" + reader.name)
console.writeline(">")
case xmlnodetype.text display the text in each element.
console.writeline(reader.value)
case xmlnodetype.endelement display end of element.
console.write("</" + reader.name)
console.writeline(">")
end select
loop
c# code
while (reader.read())
{
    switch (reader.nodetype)
    {
        case xmlnodetype.element: // the node is an element.
            console.write("<" + reader.name);
   console.writeline(">");
            break;
  case xmlnodetype.text: //display the text in each element.
            console.writeline (reader.value);
            break;
  case xmlnodetype. endelement: //display end of element.
            console.write("</" + reader.name);
   console.writeline(">");
            break;
    }
}
inspect the attributes. element node types can include a list of attribute nodes that are associated with them. the movetonextattribute method moves sequentially through each attribute in the element. use the hasattributes property to test whether the node has any attributes. the attributecount property returns the number of attributes for the current node.

visual basic .net code
do while (reader.read())
select case reader.nodetype
case xmlnodetype.element display beginning of element.
console.write("<" + reader.name)
         if reader.hasattributes then if attributes exist
             while reader.movetonextattribute()
                    display attribute name and value.
console.write(" {0}={1}", reader.name, reader.value)
end while
end if
console.writeline(">")
case xmlnodetype.text display the text in each element.
console.writeline(reader.value)
case xmlnodetype.endelement display end of element.
console.write("</" + reader.name)
console.writeline(">")
end select
loop
c# code
while (reader.read())
{
    switch (reader.nodetype)
    {
        case xmlnodetype.element: // the node is an element.
            console.write("<" + reader.name);

            while (reader.movetonextattribute()) // read attributes.
                console.write(" " + reader.name + "=" + reader.value + "");
            console.write(">");
   console.writeline(">");
            break;
  case xmlnodetype.text: //display the text in each element.
            console.writeline (reader.value);
            break;
  case xmlnodetype. endelement: //display end of element.
            console.write("</" + reader.name);
   console.writeline(">");
            break;
    }
}

completed code is provided here for your convenience.
visual basic.net code

imports system.xml
imports system.io
module module1

    sub main()
        dim stream as system.io.streamreader
         loads the xml data in the file books.xml in a new stream.
        stream = new streamreader("books.xml")
        dim reader as xmltextreader = new xmltextreader(stream)
        do while (reader.read())
            select case reader.nodetype
                case xmlnodetype.element display beginning of element.
                    console.write("<" + reader.name)
                    if reader.hasattributes then if attributes exist
                        while reader.movetonextattribute()
                            display attribute name and value.
                            console.write(" {0}={1}", reader.name, reader.value)
                        end while
                    end if
                    console.writeline(">")
                case xmlnodetype.text display the text in each element.
                    console.writeline(reader.value)
                case xmlnodetype.endelement display end of element.
                    console.write("</" + reader.name)
                    console.writeline(">")
            end select
        loop
    end sub

end module

c# code

using system;
using system.xml;
using system.io;
namespace readxmlfromstream
{
    /// <summary>
    /// summary description for class1.
    /// </summary>
    class class1
    {
        static void main(string[] args)
        {

            system.io.streamreader stream = new system.io.streamreader ("books.xml");
            xmltextreader reader = null;    
            reader = new xmltextreader (stream);
            while (reader.read())
            {
                switch (reader.nodetype)
                {
                    case xmlnodetype.element: // the node is an element.
                        console.write("<" + reader.name);

                        while (reader.movetonextattribute()) // read attributes.
                            console.write(" " + reader.name + "=" + reader.value + "");
                        console.write(">");
                        console.writeline(">");
                        break;
                    case xmlnodetype.text: //display the text in each element.
                        console.writeline (reader.value);
                        break;
                    case xmlnodetype. endelement: //display end of element.
                        console.write("</" + reader.name);
                        console.writeline(">");
                        break;
                }
            }

        }
    }
}

build and run your project.

back to the top
references
for more information, see the "xml in microsoft .net: .net framework xml classes and c# offer simple, scalable data manipulation" article from msdn magazine at the following microsoft web site:
http://msdn.microsoft.com/library/periodic/period01/xml0101.htm
for more information about the xmlreader , streamreader , and stringreader classes, see the microsoft .net framework class library documentation.

for more information about using xmlreader to read xml data, see the microsoft .net framework developers guide documentation.

back to the top  

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 »
分享到: 更多 (0)

相关推荐

  • 暂无文章