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

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