Csharp/CSharp Tutorial/XML/Xml Atrributes

Материал из .Net Framework эксперт
Версия от 12:17, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

If it is an Attribute

using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
    class Program{
        static void Main(string[] args)
        {
            XmlDocument itemDoc = new XmlDocument();
            itemDoc.Load("items.xml");
            Console.WriteLine("DocumentElement has {0} children.",itemDoc.DocumentElement.ChildNodes.Count);
            foreach (XmlNode itemNode in itemDoc.DocumentElement.ChildNodes)
            {
                XmlElement itemElement = (XmlElement)itemNode;
                Console.WriteLine("\n[Item]: {0}\n{1}", itemElement.Attributes["name"].Value,itemElement.Attributes["description"].Value);
                if (itemNode.ChildNodes.Count == 0)
                    Console.WriteLine("(No additional Information)\n");
                else
                {
                    foreach (XmlNode childNode in itemNode.ChildNodes)
                    {
                        if (childNode.Name.ToUpper() == "ATTRIBUTE")
                        {
                            Console.WriteLine("{0} : {1}",
                                childNode.Attributes["name"].Value,
                                childNode.Attributes["value"].Value);
                        }
                        else if (childNode.Name.ToUpper() == "SPECIALS")
                        {
                            foreach (XmlNode specialNode in childNode.ChildNodes)
                            {
                                Console.WriteLine("*{0}:{1}",
                                    specialNode.Attributes["name"].Value,
                                    specialNode.Attributes["description"].Value);
                            }
                        }
                    }
                }
            }
        }
    }

Using XmlAttributeOverrides with XmlSerializer

using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
    public class Customer
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
        public override string ToString()
        {
            return string.Format("{0} {1}\nEmail:   {2}",FirstName, LastName, EmailAddress);
        }
    }
    public class Tester
    {
        static void Main()
        {
            Customer c1 = new Customer{
                              FirstName = "A",
                              LastName = "G",
                              EmailAddress = "o@a.ru"
                          };
            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            Type customerType = typeof(Customer);
            foreach (PropertyInfo prop in customerType.GetProperties())
            {
                XmlAttributes attrs = new XmlAttributes();
                attrs.XmlAttribute = new XmlAttributeAttribute();
                overrides.Add(customerType, prop.Name, attrs);
            }
            XmlSerializer serializer = new XmlSerializer(customerType, overrides);
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, c1);
            string xml = writer.ToString();
            Console.WriteLine("Customer in XML:\n{0}\n", xml);
            Customer c2 = serializer.Deserialize(new StringReader(xml)) as Customer;
            Console.WriteLine("Customer in Object:\n{0}", c2.ToString());
        }
    }

Write attribute value

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;
using System.Xml.XPath;
    public class MainClass
    {
        public static void Main()
        {
            XmlDocument doc;
            XPathNavigator editor;
            XmlWriter writer;
            doc = new System.Xml.XmlDocument();
            doc.Load("pubs.xml");
            editor = doc.CreateNavigator().SelectSingleNode("/pubs");
            writer = editor.AppendChild();
            writer.WriteStartElement("publishers");
            writer.WriteAttributeString("pub_id", "1234");
            writer.WriteAttributeString("pub_name", "A");
            writer.WriteEndElement();
            writer.Close();
            doc.Save("output.xml");
        }
    }

XmlTextReader: move to content and move to first attribute

using System;
using System.Xml;
class MainClass
{
  static void Main(string[] args)
  {
    XmlTextReader reader = new XmlTextReader(@"C:\books.xml");
    
    reader.MoveToContent();
    reader.MoveToFirstAttribute();
    Console.WriteLine("First Attribute Value" +reader.Value);
    Console.WriteLine("First Attribute Name" +reader.Name);
  }
}

XmlTextReader: read all attributes

using System;
using System.Xml;
class MainClass
{
  static void Main(string[] args)
  {
    XmlTextReader reader = new XmlTextReader(@"C:\books.xml");
    
    while (reader.Read())
    {
      if (reader.HasAttributes)
      {
        Console.WriteLine(reader.Name + " Attribute");
        for (int i = 0; i < reader.AttributeCount; i++)
        {
          reader.MoveToAttribute(i);
          Console.WriteLine("Nam: "+reader.Name +", Value: "+ reader.Value);
        }
        reader.MoveToElement(); 
      }    
    }
  }
}