星期三, 10月 08, 2014

[C#] XML File

MVA Twenty C# Questions Explained - [02 How does one parse XML files?]

MVA 範例
using System.Text;
using System.Xml;

namespace MVATwentyQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
         String xmlString =
      @"
				<bookstore>
                    <book genre="autobiography" isbn="1-861003-11-0" publicationdate="1981-03-22">
                        <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>";

         ParseXml(xmlString);
        }
    }

    static void ParseXml(string xmlString)
    {
        // Create a Stringbuilder object to hold the text from the XML file 
        // that we will output later
        StringBuilder output = new StringBuilder();

        // Create an XmlReader
        using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
        {
            reader.ReadToFollowing("book");
            reader.MoveToFirstAttribute();
            string genre = reader.Value;
            output.AppendLine("The genre value: " + genre);

            reader.ReadToFollowing("title");
            output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
        }    

        Console.WriteLine(output);
    }

}
[C#] XML File-1

沒有留言:

張貼留言