شركة التطبيقات المتكاملة لتصميم النظم البرمجية الخاصة

Integrated Applications Programming Company

Skip Navigation LinksHome » Code Library » Xml

Public general use code classes and xml files that we've compiled and used over the years:

XML support class.

   1:  using System;
   2:  using System.Web;
   3:  using System.Xml;
   4:  using System.Xml.XPath;
   5:  using System.Xml.Xsl;
   6:  using System.Xml.Linq;
   7:  using System.Configuration;
   8:  using System.IO;
   9:  using System.Text;
  10:  using System.Data;
  11:  using System.Linq;
  12:   
  13:  namespace Ia.Cl.Model
  14:  {
  15:      ////////////////////////////////////////////////////////////////////////////
  16:   
  17:      /// <summary publish="true">
  18:      /// XML support class.
  19:      /// </summary>
  20:      /// <remarks> 
  21:      /// Copyright © 2001-2015 Jasem Y. Al-Shamlan (info@ia.com.kw), Internet Applications - Kuwait. All Rights Reserved.
  22:      ///
  23:      /// This library is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
  24:      /// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  25:      ///
  26:      /// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
  27:      /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  28:      /// 
  29:      /// You should have received a copy of the GNU General Public License along with this library. If not, see http://www.gnu.org/licenses.
  30:      /// 
  31:      /// Copyright notice: This notice may not be removed or altered from any source distribution.
  32:      /// </remarks> 
  33:      public class Xml
  34:      {
  35:          ////////////////////////////////////////////////////////////////////////////
  36:   
  37:          /// <summary>
  38:          ///
  39:          /// </summary>
  40:          public Xml() { }
  41:   
  42:          ////////////////////////////////////////////////////////////////////////////
  43:   
  44:          /// <summary>
  45:          ///
  46:          /// </summary>
  47:          public XmlNode ReturnXmlNode(string file)
  48:          {
  49:              return ReturnXmlNode("/", file);
  50:          }
  51:   
  52:          ////////////////////////////////////////////////////////////////////////////
  53:   
  54:          /// <summary>
  55:          ///
  56:          /// </summary>
  57:          public XmlNode ReturnXmlNode(string node_str, string file)
  58:          {
  59:              string path;
  60:              XmlNode n, m = null;
  61:              XmlDocument d = new XmlDocument();
  62:   
  63:              path = Cl.Model.Default.AbsolutePath();
  64:   
  65:              path = path + file;
  66:   
  67:              using (XmlTextReader r = new XmlTextReader(path))
  68:              {
  69:                  //r.WhitespaceHandling = WhitespaceHandling.Significant;
  70:                  d.Load(r);
  71:                  n = d.DocumentElement;
  72:                  m = n.SelectSingleNode(node_str);
  73:   
  74:                  // r.Close();
  75:              }
  76:   
  77:              return m;
  78:          }
  79:   
  80:          ////////////////////////////////////////////////////////////////////////////
  81:   
  82:          /// <summary>
  83:          ///
  84:          /// </summary>
  85:          public void WriteXmlNode(XmlNode xn, string file)
  86:          {
  87:              string path;
  88:              //XmlDocument d = new XmlDocument();
  89:              //XmlTextWriter w = null;
  90:   
  91:              //xn.WriteContentTo(w);
  92:   
  93:              try
  94:              {
  95:                  //r = new XmlTextReader(HttpContext.Current.Server.MapPath(file));
  96:                  //w.w.WhitespaceHandling = WhitespaceHandling.None;
  97:                  //n = d.DocumentElement;
  98:   
  99:                  path = global::Ia.Cl.Model.Default.AbsolutePath();
 100:   
 101:                  path = path + file;
 102:   
 103:                  string xmlContents = xn.InnerXml;
 104:                  using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path, false, System.Text.Encoding.UTF8))
 105:                  {
 106:                      writer.Write(xmlContents);
 107:   
 108:                      //writer.Close();
 109:                  }
 110:   
 111:                  //       d.DocumentElement = xn.InnerXml;
 112:                  //       FileStream fsxml = new FileStream(path,FileMode.Truncate,FileAccess.Write,FileShare.ReadWrite);
 113:   
 114:                  //       d.Save(fsxml);
 115:   
 116:                  //m = n.SelectSingleNode(node_str);
 117:   
 118:                  //if (w!=null) w.Close();
 119:              }
 120:              catch (Exception)
 121:              {
 122:  #if DEBUG
 123:                  //line += "Error: " + ex.ToString();
 124:  #else
 125:                  //line += "Error: " + ex.Message;
 126:  #endif
 127:              }
 128:              finally
 129:              {
 130:                  //if (w!=null) w.Close();
 131:              }
 132:          }
 133:   
 134:          ////////////////////////////////////////////////////////////////////////////
 135:   
 136:          /// <summary>
 137:          ///
 138:          /// </summary>
 139:          public XmlNode Literal(string s)
 140:          {
 141:              XmlNode xn = null;
 142:              XmlDocument xd = new XmlDocument();
 143:   
 144:              try
 145:              {
 146:                  xd.LoadXml(s);
 147:                  xn = xd.DocumentElement;
 148:              }
 149:              catch (Exception)
 150:              {
 151:  #if DEBUG
 152:                  //line += "Error: " + ex.ToString();
 153:  #else
 154:                  //line += "Error: " + ex.Message;
 155:  #endif
 156:              }
 157:   
 158:              return xn;
 159:          }
 160:   
 161:          ////////////////////////////////////////////////////////////////////////////
 162:   
 163:          /// <summary>
 164:          ///
 165:          /// </summary>
 166:          public DataSet Read(string file)
 167:          {
 168:              // read and return the contents of the XML file as a DataSet
 169:              string path;
 170:              DataSet ds = new DataSet();
 171:   
 172:              path = global::Ia.Cl.Model.Default.AbsolutePath();
 173:   
 174:              path = path + file;
 175:   
 176:              using (XmlTextReader xtr = new XmlTextReader(path))
 177:              {
 178:                  ds.ReadXml(xtr, XmlReadMode.ReadSchema);
 179:   
 180:                  // if (xtr != null) xtr.Close();
 181:              }
 182:   
 183:              return ds;
 184:          }
 185:   
 186:          ////////////////////////////////////////////////////////////////////////////
 187:   
 188:          /// <summary>
 189:          ///
 190:          /// </summary>
 191:          public void Write(DataSet ds, string file)
 192:          {
 193:              string path;
 194:   
 195:              path = global::Ia.Cl.Model.Default.AbsolutePath();
 196:   
 197:              path = path + file;
 198:   
 199:              using (XmlTextWriter xtw = new XmlTextWriter(path, Encoding.UTF8))
 200:              {
 201:   
 202:                  ds.WriteXml(xtw, XmlWriteMode.WriteSchema);
 203:                  //if (xtw != null) xtw.Close();
 204:              }
 205:          }
 206:   
 207:          /*
 208:              ////////////////////////////////////////////////////////////////////////////
 209:      
 210:              /// <summary>
 211:              ///
 212:              /// </summary>
 213:              public void Initialize_Data()
 214:              {
 215:                // Read XML document
 216:                xmltr = null;
 217:  
 218:                try
 219:                {
 220:                  xmltr = new XmlTextReader(HttpContext.Current.Server.MapPath("..\\data\\data.xml")); // ????
 221:                  xmltr.WhitespaceHandling = WhitespaceHandling.None;
 222:                  xmld = new XmlDocument();
 223:                  xmld.Load(xmltr);
 224:            
 225:                  // this part will set special id elements for the XML document. The id of a node is thea concatenation
 226:                  // of ids of ancestors. This will make the handling of XML data simpler. Note that this does not apply
 227:                  // for a document that does not have an id attribute.
 228:        
 229:                  // Note that this assumes any id value in the XML file will not exceed 999 (three digits)
 230:        
 231:                  XmlNode m,n = xmld.DocumentElement;
 232:                  XmlNodeList ance,list=n.SelectNodes("//*");
 233:          
 234:                  if(list.Count > 0)
 235:                  {
 236:                    // 
 237:                    foreach(XmlNode ni in list)
 238:                    {
 239:                      if(ni.Name.ToString() == "Stock") //Page")
 240:                      {
 241:                        // add the path_id attribute to node of type "Page" only:
 242:                        m = xmld.CreateNode(XmlNodeType.Attribute,"path_id",ni.NamespaceURI);
 243:                        ni.Attributes.SetNamedItem(m);
 244:  
 245:                        // 
 246:                        foreach(XmlAttribute l in ni.Attributes)
 247:                        {
 248:                          if(l.Name.ToString() == "id")
 249:                          {
 250:                            // if this is the id attribute add the id of the parents as a prefix to node path_id
 251:                            ance=ni.SelectNodes("ancestor::*");
 252:                            string id="";
 253:                    
 254:                            // l.Value = l.Value.PadLeft(3,'0');
 255:                            ni.Attributes["path_id"].Value = l.Value.PadLeft(3,'0');
 256:                 
 257:                            foreach(XmlNode ce in ance)
 258:                            {
 259:                              try
 260:                              {
 261:                                if(ce.Attributes.Count>0) id = ce.Attributes["id"].Value + id;
 262:                              }
 263:                              catch(Exception ex)
 264:                              {
 265:          #if DEBUG
 266:                                //result_l.Text += "Error: " + ex.ToString();
 267:          #else
 268:                                  //result_l.Text += "Error: " + ex.Message;
 269:          #endif
 270:                              }
 271:                      
 272:                              // replace ce.Attributes.Count with something like ce.Attributes.Contains("id")
 273:                            }
 274:  
 275:                            // this has a very important effect; it removes any leading zeros and makes the number padded but int like
 276:                            // and will be consistant with Javascript and the database tables:
 277:                            ni.Attributes["path_id"].Value = (long.Parse(id + ni.Attributes["path_id"].Value)).ToString();
 278:                          }
 279:                  
 280:                        }
 281:                      }
 282:                    }
 283:                  }
 284:            
 285:  
 286:  
 287:                }
 288:                catch (Exception ex)
 289:                {
 290:          #if DEBUG
 291:                  int i=0;
 292:                  i++;//result_l.Text += "Error: " + ex.ToString();
 293:          #else
 294:                    //result_l.Text += "Error: " + ex.Message;
 295:          #endif
 296:                }    
 297:                finally
 298:                {
 299:                  if (xmltr!=null) xmltr.Close();
 300:                }
 301:  
 302:              }
 303:  
 304:              ////////////////////////////////////////////////////////////////////////////
 305:      
 306:              /// <summary>
 307:              /// Returns tables from the XML document using the XPath. This will make the handling of XML data simpler.
 308:              /// </summary>
 309:              public DataTable Xmld(string xpath)
 310:              {
 311:                // Note that the id of elements from the XML document are special. The id of a node is a concatenation
 312:                // of ids of ancestors. This will make the handling of XML data simpler. Note that this does not apply
 313:                // for a document that does not have an id attribute.
 314:        
 315:                // Note that this assumes any id value in the XML file will not exceed 999 (three digits)
 316:        
 317:                DataTable dt = new DataTable();
 318:                DataRow dr;
 319:  
 320:                Initialize_Data();
 321:          
 322:                try
 323:                {
 324:                  XmlNode n = xmld.DocumentElement;
 325:                  XmlNodeList list=n.SelectNodes(xpath);
 326:          
 327:                  if(list.Count > 0)
 328:                  {
 329:                    // read the names of attributes and create datatable rows for them
 330:                    foreach(XmlAttribute l in list[0].Attributes)
 331:                    {
 332:                      dt.Columns.Add(new DataColumn(l.Name,typeof(string)));
 333:                    }
 334:            
 335:                    // now fill the newly created table with values from the XML
 336:                    foreach(XmlNode ni in list)
 337:                    {
 338:                      dr = dt.NewRow();
 339:                      foreach(XmlAttribute a in ni.Attributes) dr[a.Name] = a.Value;
 340:                      dt.Rows.Add(dr);
 341:                    }
 342:            
 343:                    DataColumn[] keys = new DataColumn[1];
 344:                    keys[0] = dt.Columns["id"];
 345:                    dt.PrimaryKey = keys;
 346:                  }
 347:                }
 348:                catch (Exception ex)
 349:                {
 350:          #if DEBUG
 351:                  //result_l.Text += "Error: " + ex.ToString();
 352:          #else
 353:                  //result_l.Text += "Error: " + ex.Message;
 354:          #endif
 355:                }    
 356:  
 357:                return dt;
 358:              }
 359:  
 360:           * 
 361:           
 362:           
 363:               ////////////////////////////////////////////////////////////////////////////
 364:      
 365:      /// <summary>
 366:      /// Returns tables from the XML document using the XPath. This will make the handling of XML data simpler.
 367:      /// </summary>
 368:      public DataTable Xmld(string xpath)
 369:      {
 370:        // Note that the id of elements from the XML document are special. The id of a node is a concatenation
 371:        // of ids of ancestors. This will make the handling of XML data simpler. Note that this does not apply
 372:        // for a document that does not have an id attribute.
 373:        
 374:        // Note that this assumes any id value in the XML file will not exceed 999 (three digits)
 375:        
 376:        DataTable dt = new DataTable();
 377:        DataRow dr;
 378:  
 379:        Initialize_Data();
 380:          
 381:        try
 382:        {
 383:          XmlNode n = xmld.DocumentElement;
 384:          XmlNodeList list=n.SelectNodes(xpath);
 385:          
 386:          if(list.Count > 0)
 387:          {
 388:            // read the names of attributes and create datatable rows for them
 389:            foreach(XmlAttribute l in list[0].Attributes)
 390:            {
 391:              dt.Columns.Add(new DataColumn(l.Name,typeof(string)));
 392:            }
 393:            
 394:            // now fill the newly created table with values from the XML
 395:            foreach(XmlNode ni in list)
 396:            {
 397:              dr = dt.NewRow();
 398:              foreach(XmlAttribute a in ni.Attributes) dr[a.Name] = a.Value;
 399:              dt.Rows.Add(dr);
 400:            }
 401:            
 402:            DataColumn[] keys = new DataColumn[1];
 403:            keys[0] = dt.Columns["id"];
 404:            dt.PrimaryKey = keys;
 405:          }
 406:        }
 407:        catch (Exception ex)
 408:        {
 409:  #if DEBUG
 410:          //error_l.Text += "Error: " + ex.ToString();
 411:  #else
 412:          //error_l.Text += "Error: " + ex.Message;
 413:  #endif
 414:        }    
 415:  
 416:        return dt;
 417:      }
 418:  
 419:  */
 420:   
 421:          ////////////////////////////////////////////////////////////////////////////
 422:   
 423:          /// <summary>
 424:          ///
 425:          /// </summary>
 426:          public XmlNode Xml_Xslt(string file_xml, string file_xsl)
 427:          {
 428:              // Read and XML and XSLT transformation and return a root node to the result
 429:              string path;
 430:              StringBuilder sb;
 431:              XmlNode xn = null;
 432:              XslCompiledTransform xct;
 433:              XPathDocument xpd;
 434:              XPathNavigator xpn;
 435:              XmlDocument xd;
 436:   
 437:              sb = new StringBuilder(10000);
 438:              sb.Length = 0;
 439:   
 440:              path = global::Ia.Cl.Model.Default.AbsolutePath();
 441:   
 442:              // load the XML document
 443:              xpd = new XPathDocument(path + file_xml);
 444:              xpn = xpd.CreateNavigator();
 445:              xct = new XslCompiledTransform();
 446:   
 447:              using (StringWriter sw = new StringWriter(sb))
 448:              {
 449:                  xct.Load(path + file_xsl, XsltSettings.TrustedXslt, null);
 450:   
 451:                  xct.Transform(xpn, null, sw);
 452:   
 453:                  xd = new XmlDocument();
 454:   
 455:                  //sw.Close();
 456:              }
 457:   
 458:              try
 459:              {
 460:                  xd.LoadXml(sb.ToString());
 461:                  xn = xd.DocumentElement;
 462:                  xn = xn.SelectSingleNode("/");
 463:              }
 464:              catch (Exception)
 465:              {
 466:  #if DEBUG
 467:                  //line += "Error: " + ex.ToString();
 468:  #else
 469:                  //line += "Error: " + ex.Message;
 470:  #endif
 471:              }
 472:              finally
 473:              {
 474:              }
 475:   
 476:              return xn;
 477:          }
 478:   
 479:          ////////////////////////////////////////////////////////////////////////////
 480:   
 481:          /// <summary>
 482:          ///
 483:          /// </summary>
 484:          public static XDocument Load(string filePath)
 485:          {
 486:              return XDocument.Load(global::Ia.Cl.Model.Default.AbsolutePath() + filePath);
 487:          }
 488:   
 489:          ////////////////////////////////////////////////////////////////////////////
 490:   
 491:          /// <summary>
 492:          /// Convert XmlDocument to XDocument
 493:          /// </summary>
 494:          public static XDocument DocumentToXDocumentReader(XmlDocument doc)
 495:          {
 496:              return XDocument.Load(new XmlNodeReader(doc));
 497:          }
 498:   
 499:          ////////////////////////////////////////////////////////////////////////////
 500:   
 501:          /// <summary>
 502:          ///
 503:          /// </summary>
 504:          public static XDocument Load(string filePath, string fileXslt)
 505:          {
 506:              //return XDocument.Load(global::Ia.Cl.Model.Default.Absolute_Path() + filePath);
 507:   
 508:              // Read and XML and XSLT transformation and return a root node to the result
 509:              string path, r;
 510:              StringBuilder sb;
 511:              XslCompiledTransform xct;
 512:              XPathDocument xpd;
 513:              XPathNavigator xpn;
 514:              XDocument xd;
 515:   
 516:              sb = new StringBuilder(10000);
 517:              sb.Length = 0;
 518:   
 519:              xd = null;
 520:   
 521:              path = global::Ia.Cl.Model.Default.AbsolutePath();
 522:   
 523:              // load the XML document
 524:              xpd = new XPathDocument(path + filePath);
 525:              xpn = xpd.CreateNavigator();
 526:              xct = new XslCompiledTransform();
 527:   
 528:              using (StringWriter sw = new StringWriter(sb))
 529:              {
 530:                  xct.Load(path + fileXslt, XsltSettings.TrustedXslt, null);
 531:   
 532:                  xct.Transform(xpn, null, sw);
 533:   
 534:                  //sw.Close();
 535:              }
 536:   
 537:              try
 538:              {
 539:                  xd = XDocument.Parse(sb.ToString());
 540:              }
 541:              catch (Exception ex)
 542:              {
 543:  #if DEBUG
 544:                  r = "Error: " + ex.ToString();
 545:  #else
 546:                  r = "Error: " + ex.Message;
 547:  #endif
 548:              }
 549:              finally
 550:              {
 551:              }
 552:   
 553:              return xd;
 554:          }
 555:   
 556:          ////////////////////////////////////////////////////////////////////////////
 557:          ////////////////////////////////////////////////////////////////////////////
 558:      }
 559:  }