Csharp/CSharp Tutorial/XML/XmlDocument — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:17, 26 мая 2010
Содержание
- 1 Add attribute to Xml document
- 2 Get child count
- 3 Get element by tag name
- 4 Get value from selected node
- 5 Loop Through XmlDocument Recursively
- 6 Read Write Xml
- 7 Remove child from XmlDocument
- 8 Select Root
- 9 Three ways to load Xml to XmlDocument
- 10 XmlDocument Event: node changed, node inserted and node removed
Add attribute to Xml document
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 document = new XmlDocument();
document.Load("Books.xml");
XmlElement root = document.DocumentElement;
XmlElement newBook = document.CreateElement("book");
XmlElement newTitle = document.CreateElement("title");
XmlElement newAuthor = document.CreateElement("author");
XmlElement newCode = document.CreateElement("code");
XmlText title = document.CreateTextNode("C#");
XmlText author = document.CreateTextNode("A");
XmlText code = document.CreateTextNode("1234567890");
XmlComment comment = document.CreateComment("book");
XmlAttribute newPages = document.CreateAttribute("Pages");
newPages.Value = "1000";
newBook.Attributes.Append(newPages);
newBook.AppendChild(comment);
newBook.AppendChild(newTitle);
newBook.AppendChild(newAuthor);
newBook.AppendChild(newCode);
newTitle.AppendChild(title);
newAuthor.AppendChild(author);
newCode.AppendChild(code);
root.InsertAfter(newBook, root.FirstChild);
document.Save("Books.xml");
}
}
Get child count
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()
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(Application.StartupPath + @"\employees.xml");
MessageBox.Show("Employee node contains " + doc.DocumentElement.ChildNodes.Count +" child nodes");
}
}
Get element by tag name
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.GetElementsByTagName("name");
foreach (XmlNode node in list)
{
Console.WriteLine(node.Name);
}
}
}
Get value from selected node
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()
{
XmlNode node = null;
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "/employees.xml");
node = doc.SelectSingleNode("//employee[./firstname/text()="asdf"]");
Console.WriteLine(node.Attributes["employeeid"].Value);
if (node == null)
{
MessageBox.Show("Please select Employee ID");
return;
}
Console.WriteLine(node.ChildNodes[0].InnerText);
Console.WriteLine(node.ChildNodes[1].InnerText);
Console.WriteLine(node.ChildNodes[2].InnerText);
Console.WriteLine(node.ChildNodes[3].InnerText);
}
}
Loop Through XmlDocument Recursively
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 document = new XmlDocument();
document.Load("Books.xml");
RecurseXmlDocument((XmlNode)document.DocumentElement);
}
private 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, indent + 2);
if (root.NextSibling != null)
RecurseXmlDocument(root.NextSibling, indent);
}
}
}
Read Write Xml
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);
}
}
}
}
}
}
}
Remove child from XmlDocument
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 document = new XmlDocument();
document.Load("Books.xml");
XmlElement root = document.DocumentElement;
if (root.HasChildNodes)
{
XmlNode book = root.LastChild;
root.RemoveChild(book);
document.Save("Books.xml");
}
}
}
Select Root
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.SelectSingleNode("//books");
RecurseXmlDocument(mCurrentNode);
}
private 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);
}
}
}
Three ways to load Xml to XmlDocument
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.IO;
public class MainClass
{
public static void Main()
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load("");
// FileStream stream = new FileStream(textBox1.Text, FileMode.Open);
// doc.Load(stream);
// stream.Close();
// doc.LoadXml(textBox1.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
XmlDocument Event: node changed, node inserted and node removed
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Xml;
public class MainClass{
public static void Main() {
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<Record> Some Value </Record>");
//Create the event handlers.
xmlDoc.NodeChanged += new XmlNodeChangedEventHandler(MyNodeChangedEvent);
xmlDoc.NodeInserted +=new XmlNodeChangedEventHandler(MyNodeInsertedEvent);
xmlDoc.NodeRemoved += new XmlNodeChangedEventHandler(MyNodeRemovedEvent);
XmlElement root = xmlDoc.DocumentElement;
string str = root.ToString();
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml="<F><S>Data</S></F>";
XmlElement rootNode = xmlDoc.DocumentElement;
rootNode.ReplaceChild(xmlDocFragment, rootNode.LastChild);
XmlNode node = xmlDoc.LastChild;
xmlDoc.RemoveChild(node);
}
public static void MyNodeChangedEvent(Object src, XmlNodeChangedEventArgs args)
{
Console.WriteLine("Node Changed Event Fired for node "+ args.Node.Name);
if (args.Node.Value != null)
{
Console.WriteLine(args.Node.Value);
}
}
public static void MyNodeInsertedEvent(Object src, XmlNodeChangedEventArgs args)
{
Console.WriteLine("Node Inserted Event Fired for node "+ args.Node.Name);
if (args.Node.Value != null)
{
Console.WriteLine(args.Node.Value);
}
}
public static void MyNodeRemovedEvent(Object src, XmlNodeChangedEventArgs args){
Console.WriteLine("Node Removed Event Fired for node "+ args.Node.Name);
if (args.Node.Value != null)
{
Console.WriteLine(args.Node.Value);
}
}
}
Node Inserted Event Fired for node S Node Inserted Event Fired for node #text Data Node Inserted Event Fired for node F Node Removed Event Fired for node #text Some Value Node Removed Event Fired for node F Node Inserted Event Fired for node F Node Removed Event Fired for node Record