Csharp/C Sharp/XML/Node Type

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

Read XML data from xml file: Node type, name

using System;
using System.IO;
using System.Xml;
  class TestXMLReader
  {
    static void Main(string[] args)
    {
      TestXMLReader tstObj = new TestXMLReader();
      StreamReader myStream = new StreamReader("books.xml");
      XmlTextReader xmlTxtRdr = new XmlTextReader(myStream);
      while(xmlTxtRdr.Read())
      {
        if(xmlTxtRdr.NodeType == XmlNodeType.Element 
          && xmlTxtRdr.Name == "A")
        {
          tstObj.ProcessMyDocument(xmlTxtRdr);
        }
      }
    }
    public void ProcessMyDocument(XmlTextReader reader)
    {
      Console.WriteLine("Start processing:" + reader.GetAttribute("property"));
      while(!(reader.NodeType == XmlNodeType.EndElement && reader.Name == "B")
        && reader.Read()) {
        if(reader.NodeType == XmlNodeType.Element && reader.Name == "C") {
          Console.WriteLine("itemcode:" + reader.GetAttribute("c"));
        }
      }
    }
  }
/*
<books>
  <A property="a">
    <B>text</B>
    <C c="aaa" >textg</C>
    <D>99999</D>
  </A>
</books>
*/


XmlNodeType Text

using System;
using System.Xml;
using System.IO;
using System.Text;
class MainClass {
    private static void Main() {
        FileStream fs = new FileStream("products.xml", FileMode.Create);
        XmlWriter w = XmlWriter.Create(fs);
        w.WriteStartDocument();
        w.WriteStartElement("products");
        w.WriteStartElement("product");
        w.WriteAttributeString("id", "1001");
        w.WriteElementString("productName", "Gourmet Coffee");
        w.WriteElementString("productPrice", "0.99");
        w.WriteEndElement();
        w.WriteStartElement("product");
        w.WriteAttributeString("id", "1002");
        w.WriteElementString("productName", "Blue China Tea Pot");
        w.WriteElementString("productPrice", "102.99");
        w.WriteEndElement();
        w.WriteEndElement();
        w.WriteEndDocument();
        w.Flush();
        fs.Close();
        fs = new FileStream("products.xml", FileMode.Open);
        XmlReader r = XmlReader.Create(fs);
        while (r.Read()) {
            if (r.NodeType == XmlNodeType.Element) {
                Console.WriteLine("<" + r.Name + ">");
                if (r.HasAttributes) {
                    for (int i = 0; i < r.AttributeCount; i++) {
                        Console.WriteLine("\tATTRIBUTE: " +
                          r.GetAttribute(i));
                    }
                }
            } else if (r.NodeType == XmlNodeType.Text) {
                Console.WriteLine("\tVALUE: " + r.Value);
            }
        }
    }
}


XML reader: deal with various NodeType

// Reading an XML document.
using System;
using System.Windows.Forms;
using System.Xml;
public class Test{
    static void Main() {
      XmlDocument document = new XmlDocument();
      document.Load( "books.xml" );
      XmlNodeReader reader = new XmlNodeReader( document );
      
      int depth = -1;
      while ( reader.Read() )
      {
         switch ( reader.NodeType )
         {
            case XmlNodeType.Element:
               depth++;
               TabOutput( depth );
               Console.WriteLine("<" + reader.Name + ">" + "\r\n");
               if ( reader.IsEmptyElement )
                  depth--;
               break;
            case XmlNodeType.rument:
               TabOutput( depth );
               Console.WriteLine("<!--" + reader.Value + "-->\r\n");
               break;
            case XmlNodeType.Text:
               TabOutput( depth );
               Console.WriteLine("\t" + reader.Value + "\r\n");
               break;
            case XmlNodeType.XmlDeclaration:
               TabOutput( depth );
               Console.WriteLine("<?" + reader.Name + " " + reader.Value + " ?>\r\n");
               break;
            
            case XmlNodeType.EndElement:     
               TabOutput( depth );
               Console.WriteLine("</" + reader.Name + ">\r\n");
               depth--;    
               break;  
         }
      }
   } 
   static void TabOutput( int number )
   {
      for ( int i = 0; i < number; i++ )
         Console.Write("\t");
   }
}


XML write: element, attribute, cddata, namespace and entity reference

using System;
using System.IO;
using System.Text;
using System.Xml;
public class WriteXml {
  public static void Main(string [] args) {
    XmlTextWriter writer = new XmlTextWriter(Console.Out);
    writer.Formatting = Formatting.Indented;
    writer.WriteStartDocument(true);
    writer.WriteComment("this is a comment");
    writer.WriteStartElement("root");
    writer.WriteAttributeString("id","1");
    writer.WriteStartAttribute("mynamespace", "name", "foo");
    writer.WriteString("bar");
    writer.WriteEndAttribute();
    // Write another element
    writer.WriteElementString("element1","some characters");
    writer.WriteStartElement("cdataElement");
    writer.WriteAttributeString("date",DateTime.Now.ToString());
    writer.WriteCData("< & would choke on");
    writer.WriteString("< & & & ");
    writer.WriteEndElement();
    // Write an empty element
    writer.WriteStartElement("emptyElement");
    writer.WriteEndElement();
    // Write another empty element
    writer.WriteStartElement("emptyElement","Empty");
    writer.WriteFullEndElement();
    // Write some text
    writer.WriteString("One string ");
    writer.WriteEntityRef("amp");
    writer.WriteString(" another.");
    // Close the root element
    writer.WriteEndElement();
    // End the document
    writer.WriteEndDocument();
    writer.Flush();
    writer.Close();
  }
}