Csharp/CSharp Tutorial/XML/Xml Node

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

Append element

<source lang="csharp">using System; using System.Xml; class MainClass {

 static void Main(string[] args)
 {
   XmlDocument doc = new XmlDocument();
   doc.LoadXml("<book genre="programming">" +
     "<title>Programming</title>" +
     "</book>");
   XmlNode root = doc.DocumentElement;
   XmlElement newbook = doc.CreateElement("price");
   newbook.InnerText="44.95";
   root.AppendChild(newbook);
   doc.Save(Console.Out);
 }

}</source>

<?xml version="1.0" encoding="gb2312"?>
<book genre="programming">
  Programming</title>
  <price>44.95</price>
</book>

Check for Xml node name

<source lang="csharp">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);
                           }
                       }
                   }
               }
           }
       }
   }</source>

Extract <member> elements for types

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml;

  class Program
  {
     static void Main(string[] args)
     {
        XmlDocument documentation = new XmlDocument();
        documentation.Load("a.xml");
        XmlNodeList memberNodes = documentation.SelectNodes("//member");
        List<XmlNode> typeNodes = new List<XmlNode>();
        foreach (XmlNode node in memberNodes)
        {
           if (node.Attributes["name"].Value.StartsWith("T"))
           {
              typeNodes.Add(node);
           }
        }
        Console.WriteLine("Types:");
        foreach (XmlNode node in typeNodes)
        {
           Console.WriteLine("- {0}", node.Attributes["name"].Value.Substring(2));
        }
     }
  }</source>

Find nodes by name

<source lang="csharp">using System; using System.Xml; public class MainClass {

 [STAThread]
 private static void Main()
 {
   XmlDocument doc = new XmlDocument();
       doc.Load(@"Sample.xml");
   XmlNodeList prices = doc.GetElementsByTagName("productPrice");
   
   XmlNode product = doc.GetElementsByTagName("products")[0];
   //XmlNode price = ((XmlElement)product).GetElementsByTagName("productPrice")[0];
       
       foreach (XmlNode price in prices)
   {
     Console.WriteLine(price.ChildNodes[0].Value);
   }
 }

}</source>

Get current value and depth during the XML document reading process

<source lang="csharp">using System; using System.Xml; class MainClass {

   static void Main(string[] args)
   {
       XmlTextReader reader = new XmlTextReader(@"C:\books.xml");
       while (reader.Read())
       {
           if (reader.HasValue)
           {                                       
               Console.WriteLine("Name: "+reader.Name);
               Console.WriteLine("Level of the node: " +reader.Depth.ToString());
               Console.WriteLine("Value: "+reader.Value);
           }
       }
   }

}</source>

Get <member> elements

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml;

  class Program
  {
     static void Main(string[] args)
     {
        XmlDocument documentation = new XmlDocument();
        documentation.Load("a.xml");
        XmlNodeList memberNodes = documentation.SelectNodes("//member");
        List<XmlNode> typeNodes = new List<XmlNode>();
        foreach (XmlNode node in memberNodes)
        {
           if (node.Attributes["name"].Value.StartsWith("T"))
           {
              typeNodes.Add(node);
           }
        }
        Console.WriteLine("Types:");
        foreach (XmlNode node in typeNodes)
        {
           Console.WriteLine("- {0}", node.Attributes["name"].Value.Substring(2));
        }
     }
  }</source>

Insert after

<source lang="csharp">using System; using System.Xml; class MainClass {

 static void Main(string[] args)
 {
       XmlDocument xmlDoc = new XmlDocument();
       xmlDoc.Load(@"c:\\books.xml");
       
       XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
       xmlDocFragment.InnerXml="<F>Data</F>";
       XmlNode aNode = xmlDoc.DocumentElement.FirstChild;
       aNode.InsertAfter(xmlDocFragment, aNode.LastChild);
       xmlDoc.Save(Console.Out);
   }       

}</source>

Read XML document by node type

<source lang="csharp">using System; using System.Xml; class MainClass {

   static void Main(string[] args)
   {
       int DecCounter=0, PICounter=0, DocCounter=0, CommentCounter=0, ElementCounter=0, AttributeCounter=0, TextCounter=0, WhitespaceCounter=0;
       XmlTextReader reader = new XmlTextReader(@"C:\books.xml");
       while (reader.Read())
       {
           XmlNodeType type = reader.NodeType; 
           switch (type) {
               case XmlNodeType.XmlDeclaration:
                   DecCounter++;
                   break;
               case XmlNodeType.ProcessingInstruction:
                   PICounter++;
                   break;
               case XmlNodeType.DocumentType:
                   DocCounter++;
                   break;
               case XmlNodeType.rument:
                   CommentCounter++;
                   break;
               case XmlNodeType.Element:
                   ElementCounter++;
                   if (reader.HasAttributes)
                       AttributeCounter += reader.AttributeCount;
                   break;
               case XmlNodeType.Text:
                   TextCounter++;
                   break;
               case XmlNodeType.Whitespace:
                   WhitespaceCounter++;
                   break;
           }               
       }
       Console.WriteLine("White Spaces:" +WhitespaceCounter.ToString());
       Console.WriteLine("Process Instructions:" +PICounter.ToString());
       Console.WriteLine("Declaration:" +DecCounter.ToString());
       Console.WriteLine("White Spaces:" +DocCounter.ToString());
       Console.WriteLine("Comments:" +CommentCounter.ToString());
       Console.WriteLine("Attributes:" +AttributeCounter.ToString());
   }

}</source>

Recursively display XmlNode

<source lang="csharp">using System; using System.Xml; class MainClass {

 public static void Main() 
 {
   XmlTextReader xtr = new XmlTextReader(@"c:\test.xml");
   xtr.WhitespaceHandling = WhitespaceHandling.None;
   XmlDocument xd = new XmlDocument();
   xd.Load(xtr);
   XmlNode xnodDE = xd.DocumentElement;
   ChildDisplay(xnodDE, 0);
   xtr.Close();
 }
 private static void ChildDisplay(XmlNode xnod, int level)
 {
   XmlNode xnodWorking;
   String pad = new String(" ", level * 2);
   Console.WriteLine(pad + xnod.Name + "(" + xnod.NodeType.ToString() + ": " + xnod.Value + ")");
   
   if (xnod.NodeType == XmlNodeType.Element)
   {
     XmlNamedNodeMap mapAttributes = xnod.Attributes;
     for(int i=0; i<mapAttributes.Count; i++)
     {
       Console.WriteLine(pad + " " + mapAttributes.Item(i).Name + " = " +  mapAttributes.Item(i).Value);
     }
   }
   
   if (xnod.HasChildNodes)
   {
     xnodWorking = xnod.FirstChild;
     while (xnodWorking != null)
     {
       ChildDisplay(xnodWorking, level+1);
       xnodWorking = xnodWorking.NextSibling;
     }
   }
 }

}</source>

MyTestElements(Element: )
  TestBoolean(Element: )
    #text(Text: true)

Replace Children

<source lang="csharp">using System; using System.Xml; class MainClass {

 static void Main(string[] args)
 {
       XmlDocument xmlDoc = new XmlDocument();
       xmlDoc.LoadXml("<Record> Some Value </Record>");
       
       XmlElement root = xmlDoc.DocumentElement;
       string str = root.ToString();
   XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
   xmlDocFragment.InnerXml="<F>Data</F>";
       
   XmlElement rootNode = xmlDoc.DocumentElement;
  
   rootNode.ReplaceChild(xmlDocFragment, rootNode.LastChild);
       xmlDoc.Save(Console.Out);
 }    

}</source>

<?xml version="1.0" encoding="gb2312"?>
<Record>
  <F>
    <S>Data</S>
  </F>
</Record>

Root Node

<source lang="csharp">using System; using System.Xml; class XmlWriterSamp {

 static void Main(string[] args)
 {
       XmlDocument xmlDoc = new XmlDocument();
       xmlDoc.LoadXml("<Record> Some Value </Record>");
       
       XmlElement root = xmlDoc.DocumentElement;
       string str = root.ToString();
   xmlDoc.RemoveAll();
   xmlDoc.Save(Console.Out);
 }    

}</source>

Select By Specific Author Node

<source lang="csharp">using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; public class MainClass {

   public static void Main()
   {
       XmlDocument mDocument = new XmlDocument();
       XmlNode mCurrentNode;
       mDocument.Load("XPathQuery.xml");
       mCurrentNode = mDocument.DocumentElement;
       XmlNodeList nodeList = mCurrentNode.SelectNodes("//book[author="J"]");
       DisplayList(nodeList);
   }
   static void DisplayList(XmlNodeList nodeList)
   {
       foreach (XmlNode node in nodeList)
       {
           RecurseXmlDocumentNoSiblings(node);
       }
   }
   static void RecurseXmlDocumentNoSiblings(XmlNode root)
   {
       if (root is XmlElement)
       {
           Console.WriteLine(root.Name);
           if (root.HasChildNodes)
               RecurseXmlDocument(root.FirstChild);
       }
       else if (root is XmlText)
       {
           string text = ((XmlText)root).Value;
           Console.WriteLine(text);
       }
       else if (root is XmlComment)
       {
           string text = root.Value;
           Console.WriteLine(text);
           if (root.HasChildNodes)
               RecurseXmlDocument(root.FirstChild);
       }
   }
   static void RecurseXmlDocument(XmlNode root)
   {
       if (root is XmlElement)
       {
           Console.WriteLine(root.Name);
           if (root.HasChildNodes)
               RecurseXmlDocument(root.FirstChild);
           if (root.NextSibling != null)
               RecurseXmlDocument(root.NextSibling);
       }
       else if (root is XmlText)
       {
           string text = ((XmlText)root).Value;
           Console.WriteLine(text);
       }
       else if (root is XmlComment)
       {
           string text = root.Value;
           Console.WriteLine(text);
           if (root.HasChildNodes)
               RecurseXmlDocument(root.FirstChild);
           if (root.NextSibling != null)
               RecurseXmlDocument(root.NextSibling);
       }
   }

}</source>

Select node by node text

<source lang="csharp">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()
       {
           XmlNodeList list=null;
           XmlDocument doc = new XmlDocument();
           doc.Load(Application.StartupPath + "/employees.xml");
           list = doc.SelectNodes("//employee[./firstname/text()="asdf"]");
           foreach (XmlNode node in list)
           {
               Console.WriteLine(node.Attributes["employeeid"].Value);
           }
       }
   }</source>

Select Nodes By Namespace from XmlDocument

<source lang="csharp">using System; using System.Xml; public class MainClass {

 [STAThread]
 private static void Main()
 {
   XmlDocument doc = new XmlDocument();
   doc.Load("Sample.xml");
   XmlNodeList matches = doc.GetElementsByTagName("*", "http://mycompany/OrderML");
   foreach (XmlNode node in matches)
   {
     Console.WriteLine(node.Name );
     foreach (XmlAttribute attribute in node.Attributes)
     {
       Console.WriteLine(attribute.Value);
     }
   }
 }

}</source>

Select nodes from XmlDocument

<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Net; class MainClass {

   static void Main(string[] args)
   {
       WebClient client = new WebClient();
       string rssFeed = client.DownloadString("http://blogs.apress.ru/wp-rss2.php");
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(rssFeed);
       XmlNodeList nodes = doc.SelectNodes("rss/channel/item/title");
       foreach (XmlNode node in nodes)
       {
           Console.WriteLine(node.InnerText);
       }
   }

}</source>

Write types to the console

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml;

  class Program
  {
     static void Main(string[] args)
     {
        XmlDocument documentation = new XmlDocument();
        documentation.Load("a.xml");
        XmlNodeList memberNodes = documentation.SelectNodes("//member");
        List<XmlNode> typeNodes = new List<XmlNode>();
        foreach (XmlNode node in memberNodes)
        {
           if (node.Attributes["name"].Value.StartsWith("T"))
           {
              typeNodes.Add(node);
           }
        }
        Console.WriteLine("Types:");
        foreach (XmlNode node in typeNodes)
        {
           Console.WriteLine("- {0}", node.Attributes["name"].Value.Substring(2));
        }
     }
  }</source>

XmlNode: InsertAfter FirstChild

<source lang="csharp">using System; using System.Xml; class MainClass {

 static void Main(string[] args)
 {
       XmlDocument xmlDoc = new XmlDocument();
       xmlDoc.Load(@"c:\\Sample.xml");
       
       XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
       xmlDocFragment.InnerXml="<F>Data</F>";
       XmlNode aNode = xmlDoc.DocumentElement.FirstChild;
       aNode.InsertAfter(xmlDocFragment, aNode.LastChild);
       xmlDoc.Save(Console.Out);
   }       

}</source>

Xml Node List

<source lang="csharp">using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Xml; using System.Net; public class MainClass {

   public static void Main(){
       
       string xml = new WebClient().DownloadString("http://blogs.apress.ru/wp-rss2.php");
       XmlDocument doc = new XmlDocument();
       doc.LoadXml(xml);
       ProcessNodes(doc.ChildNodes);
   }
   private static void ProcessNodes(XmlNodeList nodes)
   {
       foreach (XmlNode node in nodes)
       {
           Console.WriteLine(string.Format("{0} - {1} - {2}",node.GetType().Name, node.Name,node.Value));
           if (node.HasChildNodes)
               ProcessNodes(node.ChildNodes);
       }
   }

}</source>