Total Pageviews

Friday, 1 June 2012

Something about XML XPATH

path selection
Root/Channel/Program

path selection with attribute
Root/Channel/Program/@Title

path selection with filtering
Root/Channel/Program[@Title='Cinema' and @Time='05:20PM']
Root/Channel/Program[@Title='Cinema' or @Time>'05:20PM']


Root/Channel[@ID>10]/Program


EXAMPLE:
Suppose an xml



<?xml version="1.0" encoding="utf-8"?>
<Roles>
  <Role RoleID="1">
    <RoleName>administrator</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="2">
    <RoleName>user</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="3">
    <RoleName>Data Manager</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="4">
    <RoleName>Report Manager</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="5">
    <RoleName>customer</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="6">
    <RoleName>clerck</RoleName>
    <Status>Active</Status>
  </Role>
  <Role RoleID="7">
    <RoleName>Employee</RoleName>
    <Status>Active</Status>
  </Role>
 </Roles>

To Update an User 

private void UpdateRole(int RoleID,string RoleName,string Status)
        {
            string XmlFilePath = Server.MapPath("~/Roles.xml");
            XPathNavigator nav;
            XmlDocument docNav;
           

            docNav = new XmlDocument();

            try
            {
                docNav.Load(XmlFilePath);
                nav = docNav.CreateNavigator();
                nav.SelectSingleNode(string.Format("Roles/Role[@RoleID='{0}']/RoleName",RoleID)).SetValue(RoleName);
                nav.SelectSingleNode(string.Format("Roles/Role[@RoleID='{0}']/Status", RoleID)).SetValue(Status);
                docNav.Save(XmlFilePath);
            }

            catch (Exception ex)
            {

                throw ex;
            }

        }

And add an user node 
private void InsertRole(int RoleID, string RoleName, string Status)
        {
            try
            {
                string XmlFilePath = Server.MapPath("~/Roles.xml");


                XmlDocument docNav = new XmlDocument();
                docNav.Load(XmlFilePath);
                XmlNode NodeParent = docNav.SelectSingleNode("Roles");
                XmlNode newChild = docNav.CreateNode(XmlNodeType.Element, "Role", null);
                XmlAttribute xa = docNav.CreateAttribute("RoleID");
                xa.Value = RoleID.ToString();
                newChild.InnerXml = string.Format("<RoleName>{0}</RoleName><Status>{1}</Status>", RoleName, Status);
                newChild.Attributes.Append(xa);
                NodeParent.AppendChild(newChild);
                docNav.Save(XmlFilePath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


No comments:

Post a Comment