XML reading is needed in a recent project. The first thing I think of is to read data using LINQ (XML parsing is a little troublesome). after the project is completed, I will extract the content and take the following notes.
1. Demo. xml
Demo. xml
<? XML version = "1.0" encoding = "UTF-8" ?>
< Note >
< Conf >
< To > Infozero </ To >
< From > Lerroy </ From >
< Heading > Test Information </ Heading >
< Body > Article 1 test information </ Body >
< Title Name = "My first message" > From myself </ Title >
</ Conf >
< Conf >
< To > Infozero@163.com </ To >
< From > Text </ From >
< Heading > Always remind me </ Heading >
< Body > This is a test message! </ Body >
< Title Name = "My second message" > From others </ Title >
</ Conf >
</ Note >
2. InProgramREFERENCE The following namespace:
Using System;
Using System. LINQ;
Using System. xml. LINQ;
3. The read method is as follows:
Main function entry
Class Program
{
Static Void Main ( String [] ARGs)
{
Xdocument Doc = Xdocument. Load ( " Demo. xml " );
VaR text = From t In Doc. descendants ( " Conf " ) // Locate a node
. Where (W => W. element ( " To " ). Value. Contains ( ' @ ' )) // Use this statement to filter data.
Select New
{
To = T. element ( " To " ). Value,
Froms = T. element ( " From " ). Value,
Head = T. element ( " Heading " ). Value,
Body = T. element ( " Body " ). Value,
Title = T. element ( " Title " ). Attribute ( " Name " ). Value // Note that attribute is used here.
};
Foreach (VAR In Text)
{
Console. writeline (A. );
Console. writeline (A. froms );
Console. writeline (A. Head );
Console. writeline (A. Body );
Console. writeline (A. Title );
}
Console. readkey ();
}
}
Result:
Summary: writing to XML is really a good thing, and it greatly facilitates our programming.
---------- Subsequent supplements :-----
For the parsing of another XML format, see: http://www.cnblogs.com/portalsky/archive/2008/09/11/1289461.html
XML addition, deletion, modification query: http://www.cnblogs.com/greatverve/archive/2010/07/13/linq-to-xml-one-begin.html