Csharp/CSharp Tutorial/XML/XmlReader

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create XmlReader from Stream

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");
        XmlReader reader = XmlReader.Create(rssFeedStream);
        reader.MoveToContent();
        while (reader.ReadToFollowing("item"))
        {
            ProcessItem(reader.ReadSubtree());
        }
    }
    static void ProcessItem(XmlReader reader)
    {
        reader.ReadToFollowing("title");
        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);
        reader.ReadToFollowing("link");
        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);
        Console.WriteLine("{0}\n\t{1}", title, link);
    }
}

Read Xml output from database

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
using System.Diagnostics;
    public class MainClass
    {
        public static void Main()
        {
            SqlConnection cnn = new SqlConnection(@"data source=.\sqlexpress;initial catalog=northwind;integrated security=true");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cnn;
            cmd.rumandType = CommandType.Text;
            cmd.rumandText = "select * from Employee FOR XML AUTO";
            cnn.Open();
            XmlReader reader=cmd.ExecuteXmlReader();
            StreamWriter writer= File.CreateText(Application.StartupPath + @"\temp.xml");
            writer.Write("<root>");
            while (reader.Read())
            {
                writer.Write(reader.ReadOuterXml());
            }
            writer.Write("</root>");
            writer.Close();
            reader.Close();
            cnn.Close();
            Process.Start(Application.StartupPath + @"\temp.xml");
        }
    }

Using XmlReader to read Xml result set from database

using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
public class DirectXML
{
    private static string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";
    public static void Main() 
    {
        string SQL = "SELECT CategoryID, CategoryName, Description FROM Categories FOR XML AUTO";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand com = new SqlCommand(SQL, con);
        try
        {
            con.Open();
            XmlReader reader = com.ExecuteXmlReader();
            while (reader.Read())
            {
                Console.WriteLine(reader.Name);
                if (reader.HasAttributes)
                {
                    for (int i = 0; i < reader.AttributeCount; i++)
                    {
                        reader.MoveToAttribute(i);
                        Console.Write(reader.Name + ": " + reader.Value);
                    }
                    reader.MoveToElement();
                }
            }
            reader.Close();
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            con.Close();
        }
    }
}

XmlReader: ReadElementContentAsString

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
using System.IO;
class MainClass
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");
        XmlReader reader = XmlReader.Create(rssFeedStream);
        reader.MoveToContent();
        while (reader.ReadToFollowing("item"))
        {
            ProcessItem(reader.ReadSubtree());
        }
    }
    static void ProcessItem(XmlReader reader)
    {
        reader.ReadToFollowing("title");
        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);
        reader.ReadToFollowing("link");
        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);
        Console.WriteLine("{0}\n\t{1}", title, link);
    }
}

XmlReaderSettings and XmlWriterSettings

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
    public class MainClass
    {
        public static void Main()
        {
            XmlReader reader;
            XmlWriter writer;
            XmlReaderSettings readerSettings =new XmlReaderSettings();
            XmlWriterSettings writerSettings = new XmlWriterSettings();
            readerSettings.IgnoreComments = true;
            readerSettings.Schemas.Add(null, "pubs.xsd");
            readerSettings.ValidationType = ValidationType.None;
            writerSettings.OmitXmlDeclaration = true;
            writerSettings.Indent = true;
            writerSettings.NewLineOnAttributes = true;
            reader = XmlReader.Create("pubs.xml", readerSettings);
            writer = XmlWriter.Create("output.xml", writerSettings);
            while (reader.Read())
            {
                writer.WriteNode(reader, true);
            }
            reader.Close();
            writer.Close();
        }
    }

XmlTextReader in Action

using System;
using System.Xml;
  class XmlTextReaderSample {
    [STAThread]
    static void Main(string[] args) {
      XmlTextReader xmlTextReader = new XmlTextReader("sample.xml");
      while (xmlTextReader.Read()) {
        if (xmlTextReader.NodeType == XmlNodeType.Element) {
          Console.Out.WriteLine((new String(" ", xmlTextReader.Depth * 3)) + "Name: <" + xmlTextReader.Name +  ">; Depth: " + xmlTextReader.Depth.ToString() + "; Attributes count: " + xmlTextReader.AttributeCount.ToString() + ";");
        }
      }
    }
  }