Csharp/CSharp Tutorial/XML/XPath — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 12:17, 26 мая 2010
Содержание
- 1 Append child from XPathNavigator
- 2 Append new node to XPathNavigator
- 3 Compile XPath to create XPathExpression
- 4 Create XPathNavigator
- 5 Move to first child in XPathNavigator
- 6 Read sub tree from XPathNavigator
- 7 Select All Author Nodes
- 8 Select All Books
- 9 Select All Child Nodes
- 10 Select node with asterisk
- 11 Select XPath from XPathNavigator
- 12 Set new value through XPathNavigator
- 13 Show innter xml and outer xml from XPathNavigator
- 14 Sorting XPathExpression with XmlSortOrder.Ascending, XmlCaseOrder.None
- 15 Using XPathExpression to sort by first name
- 16 Using XPathNavigator to loop through code
- 17 Using XPathNodeIterator
- 18 Using XPath to filter data from Database
- 19 Xpath Demo: //attribute[@name="capacity"] | //attribute[@name="weight"]
- 20 Xpath Demo: /items/item
- 21 Xpath Demo: /items/item[2]
- 22 Xpath Demo: /items/item/attribute[@value > 10 and @name="weight"]
- 23 XPath Navigator
- 24 XPathNavigator and TreeView
- 25 XPath Node Iterator
- 26 XPath Selecting: /Customers/Customer[@FirstName="D"]
- 27 XPath selecting: descendant::Customer[attribute::FirstName="D"]
- 28 XPath selecting: descendant::Customer[contains(EmailAddress, "a.com")]
- 29 XPath selecting: descendant::Customer[EmailAddress="k@a.com"]
- 30 XPath selecting: descendant::Customer[@FirstName="D"]
- 31 XPath selecting: descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.com")]
- 32 XPath selecting: descendant::EmailAddress[text()="k@a.com"]
- 33 XPath Select Nodes
- 34 XPath XSLT transformation
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 editor2;
XmlWriter writer;
doc = new XmlDocument();
doc.Load("pubs.xml");
foreach(XPathNavigator editor in doc.CreateNavigator().Select("/pubs/titles[authors/@au_lname="Green"]"))
{
editor2 = editor.SelectSingleNode("authors[@au_lname!="Green"]");
if (editor2!=null) editor2.DeleteSelf();
writer = editor.AppendChild();
writer.WriteStartElement("authors");
writer.WriteAttributeString("au_lname", "A");
writer.WriteAttributeString("au_fname", "B");
writer.Close();
}
doc.Save("output.xml");
}
}
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 editor2;
XmlWriter writer;
doc = new XmlDocument();
doc.Load("pubs.xml");
doc.CreateNavigator().Select("/pubs/titles[authors/@au_lname="Green"]");
foreach(XPathNavigator editor in doc.CreateNavigator().Select("/pubs/titles[authors/@au_lname="Green"]"))
{
editor2 = editor.SelectSingleNode("authors[@au_lname!="Green"]");
if (editor2!=null) editor2.DeleteSelf();
writer = editor.AppendChild();
writer.WriteStartElement("authors");
writer.WriteAttributeString("au_lname", "A");
writer.WriteAttributeString("au_fname", "B");
writer.Close();
}
doc.Save("output.xml");
}
}
Compile XPath to create XPathExpression
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()
{
XPathDocument doc = new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
XPathExpression expression = navigator.rupile("xpath");
XPathNodeIterator iterator = navigator.Select(expression);
try
{
Console.WriteLine("The expressions returned " + iterator.Count + " nodes");
if (iterator.Count > 0)
{
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.OuterXml);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
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()
{
XPathNavigator navigator = null;
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + @"/employees.xml");
navigator = doc.CreateNavigator();
//XPathDocument doc = new XPathDocument(Application.StartupPath + @"/employees.xml");
//navigator = doc.CreateNavigator();
}
}
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()
{
XPathDocument doc=new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
XPathNavigator result=navigator.SelectSingleNode(@"employees/employee[@employeeid=1]");
result.MoveToFirstChild();
do
{
switch (result.Name)
{
case "firstname":
Console.WriteLine(result.Value);
break;
case "lastname":
Console.WriteLine(result.Value);
break;
case "homephone":
Console.WriteLine(result.Value);
break;
case "notes":
Console.WriteLine(result.Value);
break;
}
}
while (result.MoveToNext());
}
}
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()
{
XPathDocument doc=new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot();
navigator.MoveToFirstChild();
while (navigator.MoveToNext())
{
navigator.MoveToFirstChild();
do
{
string id = navigator.GetAttribute("employeeid", "");
if (id == "1")
{
XmlReader reader=navigator.ReadSubtree();
DisplayDetails(reader);
}
}
while (navigator.MoveToNext());
}
}
private static void DisplayDetails(XmlReader reader)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "firstname":
Console.WriteLine(reader.ReadString());
break;
case "lastname":
Console.WriteLine(reader.ReadString());
break;
case "homephone":
Console.WriteLine(reader.ReadString());
break;
case "notes":
Console.WriteLine(reader.ReadString());
break;
}
}
}
reader.Close();
}
}
Select All Author Nodes
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");
XmlNodeList nodeList = mCurrentNode.SelectNodes("//book/author");
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);
}
}
}
Select All Books
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");
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);
}
}
}
Select All Child Nodes
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("*");
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);
}
}
}
Select node with asterisk
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("*");
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);
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
XPathNavigator nav = customerXml.CreateNavigator();
string xPath = "descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.ru")]";
XPathNodeIterator iter = nav.Select(xPath);
if (iter.Count > 0)
{
while (iter.MoveNext())
Console.WriteLine(iter.Current.OuterXml);
}
else
Console.WriteLine("Customer not found");
}
}
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;
System.Xml.XPath.XPathNavigator editor;
doc = new XmlDocument();
doc.Load("pubs.xml");
editor = doc.CreateNavigator().SelectSingleNode("/pubs/publishers[@pub_id="0736"]/@pub_name");
editor.SetValue("new");
doc.Save("output.xml");
}
}
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()
{
XPathDocument doc=new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot();
navigator.MoveToFirstChild();
while (navigator.MoveToNext())
{
MessageBox.Show(navigator.InnerXml);
MessageBox.Show(navigator.OuterXml);
}
}
}
Sorting XPathExpression with XmlSortOrder.Ascending, XmlCaseOrder.None
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
XPathNavigator nav = customerXml.CreateNavigator();
string xPath = "descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.ru")]";
XPathNodeIterator iter = nav.Select(xPath);
XPathExpression expr2 = nav.rupile(xPath);
expr2.AddSort("@FirstName", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Text);
iter = nav.Select(expr2);
while (iter.MoveNext())
Console.WriteLine(iter.Current.OuterXml);
}
}
Using XPathExpression to sort by first name
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
XPathNavigator nav = customerXml.CreateNavigator();
string xPath = "descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.ru")]";
XPathNodeIterator iter = nav.Select(xPath);
XPathExpression expr = nav.rupile(xPath);
expr.AddSort("@FirstName", Comparer<String>.Default);
iter = nav.Select(expr);
while (iter.MoveNext())
Console.WriteLine(iter.Current.OuterXml);
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.XPath;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
XPathNavigator nav = customerXml.CreateNavigator();
string xPath = "descendant::Customer[@FirstName="D"]";
XPathNavigator navNode = nav.SelectSingleNode(xPath);
if (navNode != null)
{
Console.WriteLine(navNode.OuterXml);
XmlElement elem = navNode.UnderlyingObject as XmlElement;
if (elem != null)
Console.WriteLine(elem.OuterXml);
else
Console.WriteLine("Found the wrong node!");
}
else
Console.WriteLine("Customer not found");
}
}
Using XPathNodeIterator
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()
{
XPathDocument doc = new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
XPathNodeIterator iterator=navigator.Select("your input");
try
{
Console.WriteLine("The expressions returned " + iterator.Count + " nodes");
if (iterator.Count > 0)
{
while (iterator.MoveNext())
{
Console.WriteLine(iterator.Current.OuterXml);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Using XPath to filter data from Database
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.IO;
public class XPathSearch
{
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";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand(SQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(com);
DataSet ds = new DataSet("Northwind");
con.Open();
adapter.FillSchema(ds, SchemaType.Mapped, "Categories");
adapter.Fill(ds, "Categories");
con.Close();
XmlDataDocument dataDoc = new XmlDataDocument(ds);
string XPath;
XPath = @"//Categories[starts-with(child::CategoryName, "A")]";
XmlNodeList nodes = dataDoc.DocumentElement.SelectNodes(XPath);
foreach (XmlNode node in nodes)
{
foreach (XmlNode child in node.ChildNodes)
{
Console.WriteLine(child.InnerText);
}
}
}
}
Xpath Demo: //attribute[@name="capacity"] | //attribute[@name="weight"]
using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
XmlDocument docItems = new XmlDocument();
docItems.Load("items.xml");
XmlNodeList cw = docItems.SelectNodes("//attribute[@name="capacity"] | //attribute[@name="weight"]");
Console.WriteLine("Heavy Items (descendant axis predicate):");
}
}
Xpath Demo: /items/item
using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
XmlDocument docItems = new XmlDocument();
docItems.Load("items.xml");
XmlNodeList allItems = docItems.SelectNodes("/items/item");
Console.WriteLine("Found {0} items", allItems.Count);
}
}
Xpath Demo: /items/item[2]
using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
XmlDocument docItems = new XmlDocument();
docItems.Load("items.xml");
XmlNode thirdItem = docItems.SelectSingleNode("/items/item[2]");
Console.WriteLine("Third node is {0}", thirdItem.Attributes["name"].Value);
}
}
Xpath Demo: /items/item/attribute[@value > 10 and @name="weight"]
using System;
using System.Xml;
using System.Collections.Generic;
using System.Text;
class Program
{
static void Main(string[] args)
{
XmlDocument docItems = new XmlDocument();
docItems.Load("items.xml");
XmlNodeList heavyAttribs = docItems.SelectNodes("/items/item/attribute[@value > 10 and @name="weight"]");
foreach (XmlNode heavyAttrib in heavyAttribs)
{
Console.WriteLine(heavyAttrib.ParentNode.Attributes["name"].Value);
}
}
}
using System;
using System.Xml.XPath;
class XPathNavigatorSample {
[STAThread]
static void Main(string[] args) {
XPathDocument xpathDocument = new XPathDocument("../../sample.xml");
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
xpathNavigator.MoveToRoot();
NavigateTree(xpathNavigator);
}
private static void NavigateTree (XPathNavigator xpathNavigator) {
if (xpathNavigator.HasChildren) {
xpathNavigator.MoveToFirstChild();
DisplayNode(xpathNavigator);
NavigateTree(xpathNavigator);
while (xpathNavigator.MoveToNext()) {
DisplayNode(xpathNavigator);
NavigateTree(xpathNavigator);
}
xpathNavigator.MoveToParent();
}
}
private static void DisplayNode (XPathNavigator xpathNavigator) {
if (xpathNavigator.NodeType == XPathNodeType.Text) {
Console.Out.WriteLine(xpathNavigator.Value);
} else {
Console.Out.Write(xpathNavigator.Name);
if (xpathNavigator.HasAttributes) {
int attributesCount = 1;
while (xpathNavigator.MoveToNextAttribute()) {
attributesCount ++;
}
Console.Out.Write(attributesCount);
if (attributesCount != 1) {
xpathNavigator.MoveToParent();
}
}
}
}
}
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 Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
XPathDocument doc = new XPathDocument(Application.StartupPath + @"\employees.xml");
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot();
navigator.MoveToFirstChild();
TreeNode root = treeView1.Nodes.Add("Employees");
while (navigator.MoveToNext())
{
if (navigator.HasChildren)
{
navigator.MoveToFirstChild();
do
{
string id = navigator.GetAttribute("employeeid", "");
TreeNode empnode = new TreeNode("Employee ID :" + id);
root.Nodes.Add(empnode);
navigator.MoveToFirstChild();
do
{
string name = navigator.Name;
TreeNode node = new TreeNode(name + " : " + navigator.Value);
empnode.Nodes.Add(node);
}
while (navigator.MoveToNext());
navigator.MoveToParent();
}
while (navigator.MoveToNext());
}
}
}
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(120, 224);
this.button1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(100, 28);
this.button1.TabIndex = 0;
this.button1.Text = "Load Tree";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Top;
this.treeView1.Location = new System.Drawing.Point(0, 0);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(329, 216);
this.treeView1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(329, 262);
this.Controls.Add(this.treeView1);
this.Controls.Add(this.button1);
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TreeView treeView1;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
XPath Node Iterator
using System;
using System.Xml.XPath;
class MainClass{
static void Main(string[] args) {
XPathDocument xpathDocument = new XPathDocument("sample.xml");
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
XPathNodeIterator xpathNodeIterator = xpathNavigator.Select("//companies/cell-phone[last()]");
int i = 0;
Console.Out.WriteLine(xpathNodeIterator.Count);
while (xpathNodeIterator.MoveNext()) {
Console.Out.WriteLine((++i) + ". Name: <" + xpathNodeIterator.Current.Name + ">. Value: " + xpathNodeIterator.Current.Value + ".");
}
}
}
XPath Selecting: /Customers/Customer[@FirstName="D"]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "/Customers/Customer[@FirstName="D"]";
XmlNode oneCustomer = customerXml.SelectSingleNode(xPath);
if (oneCustomer != null)
Console.WriteLine(oneCustomer.OuterXml);
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::Customer[attribute::FirstName="D"]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::Customer[attribute::FirstName="D"]";
XmlElement oneCustomer = (XmlElement)customerXml.SelectSingleNode(xPath);
if (oneCustomer != null)
Console.WriteLine(oneCustomer.OuterXml);
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::Customer[contains(EmailAddress, "a.com")]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::Customer[contains(EmailAddress, "a.ru")]";
XmlNodeList customerList = customerXml.SelectNodes(xPath);
Console.WriteLine("\nSelectNodes(\"{0}\")...", xPath);
if (customerList != null)
{
foreach (XmlNode customer in customerList)
Console.WriteLine(customer.OuterXml);
}
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::Customer[EmailAddress="k@a.com"]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::Customer[EmailAddress="k@a.ru"]";
XmlElement oneCustomer = (XmlElement)customerXml.SelectSingleNode(xPath);
Console.WriteLine("\nSelectSingleNode(\"{0}\")...", xPath);
if (oneCustomer != null)
Console.WriteLine(oneCustomer.OuterXml);
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::Customer[@FirstName="D"]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::Customer[@FirstName="D"]";
XmlNode oneCustomer = customerXml.SelectSingleNode(xPath);
Console.WriteLine("\nSelectSingleNode(\"{0}\")...", xPath);
if (oneCustomer != null)
Console.WriteLine(oneCustomer.OuterXml);
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.com")]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::Customer[starts-with(@LastName, "G") and contains(EmailAddress, "a.ru")]";
XmlNodeList customerList = customerXml.SelectNodes(xPath);
if (customerList != null)
{
foreach (XmlNode customer in customerList)
Console.WriteLine(customer.OuterXml);
}
else
Console.WriteLine("Not found");
}
}
XPath selecting: descendant::EmailAddress[text()="k@a.com"]
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
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()
{
List<Customer> customers = new List<Customer>{
new Customer { FirstName = "A",
LastName = "G",
EmailAddress = "o@a.ru"},
new Customer { FirstName = "B",
LastName = "C",
EmailAddress = "k@a.ru" },
new Customer { FirstName = "D",
LastName = "C",
EmailAddress = "d@a.ru" },
new Customer { FirstName = "E",
LastName = "G",
EmailAddress = "j@a.ru" },
new Customer { FirstName = "L",
LastName = "H",
EmailAddress = "l@a.ru" }
};
XmlDocument customerXml = new XmlDocument();
XmlElement rootElem = customerXml.CreateElement("Customers");
customerXml.AppendChild(rootElem);
foreach (Customer customer in customers)
{
XmlElement customerElem = customerXml.CreateElement("Customer");
XmlAttribute firstNameAttr = customerXml.CreateAttribute("FirstName");
firstNameAttr.Value = customer.FirstName;
customerElem.Attributes.Append(firstNameAttr);
XmlAttribute lastNameAttr = customerXml.CreateAttribute("LastName");
lastNameAttr.Value = customer.LastName;
customerElem.Attributes.Append(lastNameAttr);
XmlElement emailAddress = customerXml.CreateElement("EmailAddress");
emailAddress.InnerText = customer.EmailAddress;
customerElem.AppendChild(emailAddress);
rootElem.AppendChild(customerElem);
}
string xPath = "descendant::EmailAddress[text()="k@a.ru"]";
XmlNode oneEmail = customerXml.SelectSingleNode(xPath);
if (oneEmail != null)
Console.WriteLine(oneEmail.OuterXml);
else
Console.WriteLine("Not found");
}
}
XPath Select Nodes
using System;
using System.Xml;
public class MainClass
{
[STAThread]
private static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("Sample.xml");
XmlNodeList nodes = doc.SelectNodes("/Order/Items/Item/Name");
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
}
}
XPath XSLT transformation
using System;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
class MainClass {
[STAThread]
static void Main(string[] args) {
XslTransform xslTransform = new XslTransform();
XPathDocument xpathDocument = new XPathDocument("../../sample.xml");
XmlTextWriter xmlTextWriter = new XmlTextWriter("../../sample.html", null);
xslTransform.Load("../../sample.xslt");
xslTransform.Transform(xpathDocument, null, xmlTextWriter);
}
}