Sunday, September 7, 2008

XML CRUD using XPath

Empire Burlesque

Xml File
--------------------------------------------------------

<?xml version="1.0" encoding="ISO-8859-1"?>

<catalog>

<cd country="USA">

<title>Empire Burlesque</title>

<artist>Bob Dylan</artist>

<price>10.90</price>

</cd>

<cd country="UK">

<title>Hide your heart</title>

<artist>Bonnie Tyler</artist>

<price>10.0</price>

</cd>

<cd country="USA">

<title>Greatest Hits</title>

<artist>Dolly Parton</artist>

<price>9.90</price>

</cd>

</catalog>




Load and Display XML File

using System.Xml;
using System.Xml.XPath;
....


string fileName = "data.xml";
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();


// Compile a standard XPath expression

XPathExpression expr;
expr = nav.Compile("/catalog/cd/price");
XPathNodeIterator iterator = nav.Select(expr);

// Iterate on the node set
listBox1.Items.Clear();


try
{


while (iterator.MoveNext())
{

XPathNavigator nav2 = iterator.Current.Clone();

listBox1.Items.Add("price: " + nav2.Value);

}

}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}


Find and Update

XmlTextReader reader = new XmlTextReader(FILE_NAME);

XmlDocument doc = new XmlDocument();

doc.Load(reader);
reader.Close();




//Select the cd node with the matching title

XmlNode oldCd;

XmlElement root = doc.DocumentElement;

oldCd = root.SelectSingleNode("/catalog/cd[title='" + oldTitle + "']");


XmlElement newCd = doc.CreateElement("cd");

newCd.SetAttribute("country",country.Text);


newCd.InnerXml = "<title>" + this.comboBox1.Text + "</title>" +
"<artist>" + artist.Text + "</artist>" +
"<price>" + price.Text + "</price>";


root.ReplaceChild(newCd, oldCd);


//save the output to a file

doc.Save(FILE_NAME);



Insert NODE to XML file


XmlTextReader reader = new XmlTextReader(FILE_NAME);

XmlDocument doc = new XmlDocument();

doc.Load(reader);

reader.Close();


XmlNode currNode;

XmlDocumentFragment docFrag = doc.CreateDocumentFragment();

docFrag.InnerXml="<cd country=\"" + country.Text + "\">" +
"<title>" + this.comboBox1.Text + "</title>" +
"<artist>" + artist.Text + "</artist>" +
"<price>" + price.Text + "</price>" +
"</cd>";

// insert the availability node into the document

currNode = doc.DocumentElement;

currNode.InsertAfter(docFrag, currNode.LastChild);


//save the output to a file

doc.Save(FILE_NAME);


Remove NODE

XmlTextReader reader = new XmlTextReader(FILE_NAME);

XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();

//Select the cd node with the matching title
XmlNode cd;
XmlElement root = doc.DocumentElement;
cd = root.SelectSingleNode("/catalog/cd[title='" + this.comboBox1.Text + "']");
root.RemoveChild(cd);

//save the output to a file
doc.Save(FILE_NAME);


Refrence : http://www.codeproject.com/KB/cpp/myXPath.aspx

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.