ArticleDirectory
- Write XML files
- Read XML files
Stream-based XML Processing
. NET framework allows you to use a group of classes in the system. xml namespace (and its sub-namespace) to operate XML data. There are two stream-based classes: xmltextreader and xmltextwriter, which are very effective for simple XML processing.
Write XML files
. Net writes XML data to a file in two ways:
- You can use the xmldocument or xdocument class in the memory to create a document and write it into the file at the end.
- Use xmltextwrite to directly write documents to the stream. When you write data, the data is output one by one.
- The preceding three classes allow information to be written to any stream. Therefore, XML data can also be written to other storage locations, such as text fields in the database.
The following example shows how to use xmltextwriter to create an XML file in good format:
Private VoidWritexml ()
{
StringXmlfile = server. mappath ("Dvdlist. xml");
// The second parameter can pass a system. Text. Encoding encoding.
// Pass an empty reference to indicate the use of standard UTF-8 Encoding
Xmltextwriter writer =NewXmltextwriter (xmlfile,Null);
// Formatting. indented indicates that indentation is used.
// Formatting. None indicates no special format is applied (default)
// Indentation indicates indentation with 3 Spaces
Writer. Formatting = formatting. indented;
Writer. indentation = 3;
// Write an XML declaration with the version "1.0"
Writer. writestartdocument ();
// Write comments containing the specified text <! --... -->
Writer. writecomment ("Creaded @"+ Datetime. Now. tostring ());
// Write the Start mark with the specified local name
Writer. writestartelement ("Dvdlist");
Writer. writestartelement ("DVD");
Writer. writeattributestring ("ID","1");
Writer. writeattributestring ("Category","Science Fiction");
// The following elements do not contain child elements, so writestartelement () is not required ()
Writer. writeelementstring ("Title","The Matrix");
Writer. writeelementstring ("Director","Larry wachoski");
Writer. writeelementstring ("Price","18.74");
// The following starring contains one or more elements.
// Use writestartelement ()
Writer. writestartelement ("Starring");
Writer. writeelementstring ("Star","Keanu Reeves");
Writer. writeelementstring ("Star","Laurence Fishburne");
// Close all opened labels in reverse order
Writer. writeendelement ();
Writer. writeendelement ();
// Create another DVD Element
Writer. writestartelement ("DVD");
Writer. writeattributestring ("ID","2");
Writer. writeattributestring ("Category","Drama");
Writer. writeelementstring ("Title","Forrest Gump");
Writer. writeelementstring ("Director","Robert Zemeckis");
Writer. writeelementstring ("Price","23.99");
Writer. writestartelement ("Starring");
Writer. writeelementstring ("Star","Tom Hanks");
Writer. writeelementstring ("Star","Robin Wright");
Writer. writeendelement ();
Writer. writeendelement ();
Writer. writeendelement ();
Writer. Close ();
}
If you want to give it a unique XML namespace to identify the XML document, the elements also need to be placed in this namespace. To do this, use writeattributestring () to output an xmlns feature. This feature is usually added to the root element of the document or the first namespace element. Second, the element name must be limited by the namespace prefix. This can be achieved through the writestartelement () method's overloaded version.
Read XML files
- You can use the xmldocument, xpathnavigator (read-only), and xdocument classes to load documents to the memory at one time.
- Xmltextreader class (Stream-based reader), a node that reads documents each time.
The stream-based method reduces the memory burden. However, if you perform time-consuming tasks on the XML document or choose to operate in the memory to avoid affecting others' access to the XML document.
Xmltextreader reading XML files is simple, but it is also the most inflexible. Files are read in sequence and cannot be moved to parent, child, or sibling nodes as freely as XML in the memory.
The followingCodeLoad the source file and start the cycle of moving a file node each time:
Private StringReadxml ()
{
StringXmlfile = server. mappath ("Dvdlist. xml");
Xmltextreader reader =NewXmltextreader (xmlfile );
Stringbuilder STR =NewStringbuilder ();
While(Reader. Read ())
{
Switch(Reader. nodetype)
{
CaseXmlnodetype. element:
Str. append ("Element: <B>"). Append (reader. Name). append ("</B> <br/>");
Break;
CaseXmlnodetype. Text:
Str. append ("-Value: <B>"). Append (reader. Value). append ("</B> <br/>");
Break;
CaseXmlnodetype. xmldeclaration:
Str. append ("XML Declaration: <B>");
Str. append (reader. Name). append (""). Append (reader. Value). append ("</B> <br/>");
Break;
}
If(Reader. attributecount> 0)
{
While(Reader. movetonextattribute ())
{
Str. append ("-Attribute: <B>"). Append (reader. Name );
Str. append ("</B> value: <B>"). Append (reader. Value). append ("</B> <br/>");
}
}
}
Reader. Close ();
ReturnStr. tostring ();
}
When using xmltextreader, you must end the task and close the reader as quickly as possible because it has a lock on the file.
The following code retrieves data from the DVD List in a more intuitive way:
Private StringReadxml ()
{
StringXmlfile = server. mappath ("Dvdlist. xml");
Xmltextreader reader =NewXmltextreader (xmlfile );
Stringbuilder STR =NewStringbuilder ();
Reader. readstartelement ("Dvdlist");
While(Reader. Read ())
{
If(Reader. Name ="DVD"& Reader. nodetype = xmlnodetype. element)
{
Reader. readstartelement ("DVD");
Str. append ("<Ul> <B>");
Str. append (reader. readelementstring ("Title"));
Str. append ("</B> <li>");
Str. append (reader. readelementstring ("Director"));
Str. append ("</LI> <li>");
Str. append (String. Format ("{0: c }", Decimal. parse (reader. readelementstring ("Price"))));
Str. append ("</LI> </ul>");
}
}
Reader. Close ();
ReturnStr. tostring ();
}