发布新日志

  • Python语言入门-函数

    2010-09-01 13:54:07

    <DIV>函数的相关语句</DIV> <DIV>语句&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;例子 </DIV> <DIV>——————————————————————————————————</DIV> <DIV>调用函数&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | myfunc("spam, ham, toast\n")</DIV> <DIV>——————————————————————————————————</DIV> <DIV>def return&nbsp;&nbsp;&nbsp; | def adder(a,b,c=1,*d): return a+b+c+d[0]</DIV> <DIV>——————————————————————————————————</DIV> <DIV>global&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | def function(): global x, y; x='New'<BR>——————————————————————————————————</DIV> <DIV>________________________________</DIV> <DIV>def 生成一个函数对象并赋给它一个名字</DIV> <DIV>return 给调用者返回一个结果对象&nbsp;&nbsp;&nbsp;</DIV> <DIV>global 声明模块级被赋值的变量&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</DIV> <DIV>参数通过赋值传递(对象引用)<BR>参数,返回类型和变量不用声明</DIV> <DIV>———————————————————</DIV><DIV>&nbsp;</DIV> <DIV>——————————————————————<BR>一般形式 def&lt;名字&gt; (arg1,arg2,...argK):<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;语句&gt;</DIV> <DIV>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return &lt;值&gt;</DIV> <DIV>return是可选的,没有return语句的函数自动返回一个None对象</DIV> <DIV>——————————————————————</DIV> <DIV>#!/usr/bin/env python</DIV> <DIV>def intersect(seq1,seq2):&nbsp;&nbsp; <BR>&nbsp;&nbsp;&nbsp; res=[]<BR>&nbsp;&nbsp;&nbsp; for x in seq1:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if x in seq2:<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; res.append(x)<BR>&nbsp;&nbsp;&nbsp; return res</DIV> <DIV>s1="SPAM"<BR>s2="SCAM"</DIV> <DIV>print(intersect(s1,s2))<BR>print(intersect([1,2,3],(1,4)))<BR></DIV> <DIV>Output:<BR>['S', 'A', 'M']<BR>[1]</DIV> <DIV>—————————————————————————————————————<BR>作用域:<BR>模块是一个全局作用域: 每一个模块是一个全局作用域-一个名字空间,变量名在一个模块文件顶层生成</DIV> <DIV>每次调用一个函数,生成一个新的局部作用域---是在函数的内部生成的名字所在的一个名字空间</DIV> <DIV>LGB--&gt; Local-&gt; Global-&gt; Build in</DIV> <DIV>—————————————————————————————————————</DIV> <DIV>#!/usr/bin/env python</DIV> <DIV>def changer(x,y):<BR>&nbsp;&nbsp;&nbsp; x=2<BR>&nbsp;&nbsp;&nbsp; y[0]='spam'</DIV> <DIV>X=1<BR>L=[1,2]<BR>print("Before Change: x=",X)<BR>print("Before Change: y=",L)<BR>changer(X,L)<BR>print("After change: x=",X)<BR>print("After change: y=",L)</DIV> <DIV>&nbsp;</DIV> <DIV>result:<BR>('Before Change: x=', 1)<BR>('Before Change: y=', [1, 2])<BR>('After change: x=', 1)<BR>('After change: y=', ['spam', 2])<BR>——————————————————————————————<BR>不可变参数作用类似于C中的“传值”模式</DIV> <DIV>可变参数作用类似于C的“传指针”模式<BR>——————————————————————————————</DIV> <DIV>&nbsp;</DIV> <DIV>***************************************************</DIV> <DIV>当关键字参数在函数中使用时,参数列出的顺序无关紧要;Python通过名字而不是位置匹配</DIV> <DIV>在调用中,关键字参数必须出现在所有非关键字参数后</DIV> <DIV>在一个函数中,*name必须在普通参数和默认值后,**name必须在最后</DIV> <DIV>*name在一个元祖中收集了任何其他位置上的参数</DIV> <DIV>**name的形式在字典中收集了其他的关键字参数</DIV> <DIV>***************************************************</DIV> <DIV>&nbsp;</DIV> <DIV>除了def语句,Python还提供了一个可以生成函数对象的表达式。应为它与LISP语言的一个工具类似所以叫lambda</DIV> <DIV>lambda 是一个表达式,不是一个语句,lambda可以出现在一个def语句所不能出现的地方-----如在一个列表常量的内部</DIV> <DIV>lambda 参数1,参数2,...参数N: 使用参数的表达式</DIV> <DIV>lambda的结构体是一个单一的表达式,不是语句块 不能使用if这样的语句</DIV> <DIV>—————————————————————————————————————</DIV> <DIV>&nbsp;</DIV> <DIV>def func(x,y,z):return x+y+z</DIV> <DIV>func(2,3,4)</DIV><DIV>&nbsp;</DIV> <DIV>f=lambda x,y,z: x+y+z</DIV><DIV>f(2,3,4)</DIV> <DIV>&nbsp;</DIV><DIV>#!/usr/bin/env python</DIV> <DIV>L=[lambda x:x**2,lambda x:x**3,lambda x:x**4]</DIV> <DIV>for f in L:<BR>&nbsp;&nbsp;&nbsp; print f(2)</DIV> <DIV>print L[0](3)<BR>4<BR>8<BR>16<BR>9<BR>————————————————————————————————————</DIV> <DIV>有的程序需要调用任意的参数,而无需事先知道它们的名字活参数。内置函数apply可以做到这一点</DIV> <DIV>if &lt;test&gt;:<BR></DIV> <DIV>&nbsp;</DIV><DIV>&nbsp;</DIV> <DIV>&nbsp;</DIV><DIV>&nbsp;</DIV> <DIV>&nbsp;</DIV>
  • 速度测试-未完成

    2010-08-31 17:51:48

    'Declare Variables
    Dim TestData_Location
    Dim Login_Check
    Dim TestCase
    Dim start_Column
    Dim start_Row
    Dim brand_Row
    Dim brand_Column
    Dim TestPC    'The PC you want to test
    Dim TestDevice 'The device you want to test "4K_001, 4K_003, C028"
    Dim record_PC 'Find the Test PC row number in the Excel'
    Dim record_row 'Find the Test device row number in the Excel'
    Dim WorkingDir
    Dim CreateFile_template
    Dim testdataFolder
    Dim fileszie
    Dim sourceFolder
    Dim CF_Storage
    Dim Copy_Check

    'initiate Variable
    TestData_Location=""
    Login_Check=Log_in("")
    TestCase="C:\test.xls"
    start_Column=66
    start_Row=3
    brand_Row=17
    brand_Column=72
    TestPC="##"
    TestDevice="##"
    WorkingDir="C:\Integration_test"
    CreateFile_template="C:\test.txt"
    testdataFolder="11"
    sourceFolder="22"
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const sourceFile = "##"
    CF_Storage=GetDriveLetter("CF_Storage")

    OpenExcel()
    Update_Result()

    'Make sure your are authorized to access the server
    Public Function  Log_in(ip,user,pw)
        Set bjShell=CreateObject("Wscript.Shell")
        objShell.Run ip
        Set bjShell=nothing
      
        Set fso=CreateObject("Scripting.FileSystemObject")
       If fso.FileExists(TestData_Location) Then
         Log_in=True
        Else
         Log_in=False
        End If
    Set fso=nothing
    End Function

    Public Function OpenExcel()
     Set fso=CreateObject("Scripting.FileSystemObject")
     Set Excel=CreateObject("Excel.Application")
     oExcel.Visible=True
     
     'Check if the test case is Exist
     If fso.FileExists(TestCase)Then
      Set bjWorkBook = oExcel.Workbooks.Open(TestCase)
      sheet_count=oExcel.Sheets.Count
      oExcel.Sheets.Item(sheet_count).Select
      Set bjSheet=oExcel.Sheets(sheet_count)
      With objSheet
         For i=start_Row To brand_Row
          If RegExpTest(TestPC,.Range(Chr(start_Column)+CStr(i))) Then
           Exit For
          End if      
         Next
         record_PC=i
         For i=record_PC+2 To record_row+4
          If RegExpTest(TestDevice,.Range(Chr(start_Column)+CStr(i))) Then
           Exit For
          End if
         Next
         record_row=i
            For i=start_Column+1 To  brand_Column
             If RegExpTest("8G",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record_8G()
             ElseIf RegExpTest("1k",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record(512)
             ElseIf RegExpTest("2k",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record(1024)
             ElseIf RegExpTest("4k",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record(2048)
             ElseIf RegExpTest("8k",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record(4096)
             ElseIf RegExpTest("16k",.Range(Chr(i)+CStr(record_PC))) Then
              Call Record(8192)
             Else
              MsgBox "Error, wrong case name"
             End if
            Next
            End with
     End If
     oExcel.Quit
     Set Excel=nothing
     Set fso=Nothing
    End Function

    Public Function Record_8G()
     Set fso=CreateObject("Scripting.FileSystemObject")
      If Not fso.FolderExists(WorkingDir+"\")Then
       fso.CreateFolder WorkingDir+"\"
      End If
      If Not fso.FolderExists(WorkingDir+"\8G") Then
       fso.CreateFolder WorkingDir+"\8G"
      End if
      If fso.FileExists("##") then
       fso.CopyFile "##", WorkingDir+"\8G\"
      End If
      If fso.FileExists( WorkingDir+"\"+"OfficeGuardain.zip") Then
       UnzipFile WorkingDir+"\"+"OfficeGuardain.zip",WorkingDir+"\8G"
      End if
     Set fso=nothing
    End Function

    Public Function Record(perFile)
     Dim copyTime
     CreateFiles(perFile)
     Copy59Times(perFile)
    End Function

    Function RegExpTest(patrn, strng)
      Dim regEx, Match, Matches  
      Set regEx = New RegExp  
      regEx.Pattern = patrn 
      regEx.IgnoreCase = True 
      regEx.Global = True 
      If regEx.Test(strng) Then
       RegExpTest=True
      Else
        RegExpTest=False
      End if
    End Function

    Public Function UnzipFile(file_zip_location, file_unzip_location)
        winRarLocation = "C:\Program Files\WinRAR\WinRAR.exe"
        zipToFolder = file_unzip_location
        dataCab_location=file_zip_location
        unzipCommand = "cmd /k CD C:\&"+chr(34)+winRarLocation+chr(34) + " x " + dataCab_location + " " + zipToFolder
        Set bjShell=CreateObject("Wscript.Shell")
        objShell.Run unzipCommand
        Set bjShell=nothing

        set pro = getobject("winmgmts:\\.").instancesof("Win32_Process")
     Do
      check_process=false
      For each ps in pro  
       If UCase(ps.name)="WINRAR.EXE" Then
        WScript.Sleep 10000
        check_process=true
        Exit For
               End If

            Next

       If check_process=true Then
        WScript.Sleep 10000
       Else
         UnzipFile=True
         Exit Do
        End If
        Set pro = getobject("winmgmts:\\.").instancesof("Win32_Process")
        Loop
       
        Set pro = getobject("winmgmts:\\.").instancesof("Win32_Process")
       
     For each ps in pro
      If UCase(ps.name)="CMD.EXE" Then
       ps.Terminate
      End If
     Next
     Set  pro=nothing
    End Function

    Public Function CreateFiles(perFile)
       filesize = CInt(perFile)

      
       WorkingDir_temp=WorkingDir+"\"+CStr(perFile)+"\"
       File_Copied_Location=WorkingDir_temp+sourceFile

       Set bjFso=CreateObject("Scripting.FileSystemObject")
       If Not objFso.FolderExists(WorkingDir_temp)then
        objFso.CreateFolder(WorkingDir_temp)
       Else
        copyCheck=False
        Exit Function
       End If

       'objFso.CopyFile CreateFile_template,WorkingDir_temp
       Set bjFso=nothing
       currentFolder=WorkingDir_temp
      
       Wscript.Echo ("MakeSure your folder&file exist, Starting...")

       Dim fso, MyFile, testFolder
       testFolder = currentFolder + "\" + testdataFolder
       Set fso = CreateObject("Scripting.FileSystemObject")
      
       If fso.FolderExists (testFolder  ) Then
          fso.DeleteFolder( testFolder  )
       End If
       fso.CreateFolder ( testFolder )

      
      'Set MyFile = fso.OpenTextFile( currentFolder + "\" + sourceFile, ForReading , True)
      Set MyFile = fso.OpenTextFile( CreateFile_template, ForReading , True)
      ReadLineTextFile MyFile, WorkingDir_temp,filesize
      MyFile.Close
      Wscript.Echo ("Create Finished")
    End Function

    Sub ReadLineTextFile (File,strPath,filesize)
       Dim nCount, folder, ret, LineText
       nCount=1
       'folder = ""
      
       'Do Until IsNull( LineText ) 'or (nCount>20)
        Do Until File.AtEndofStream  
           LineText = File.ReadLine   
            'Wscript.Echo LineText
      'Wscript.Echo ( QueryStr (LineText ) )   
            ret = QueryStr( LineText,folder,strPath,filesize )
            If Not IsNull(ret) Then
              folder = ret
             End If
            'nCount=nCount+1
        Loop
    End Sub

    Function QueryStr( SourceStr, SubFolder,strPath1,filesize)

      Dim str1, str2, retStr, retStr1, nPos1, nPos2
      Dim fso1, f1, strPath
      Set fso1 = CreateObject("Scripting.FileSystemObject")
      strPath = strPath1+ testdataFolder

      str1="[ ]"
      str2=" - "

      nPos1 = InStr( SourceStr, str1 )
      'nPos2 = Instr( Right(SourceStr, Len(SourceStr)-nPos1), str2 )
       nPos2 = InStr( SourceStr, str2 )
      If nPos1=0 then
         QueryStr = Null
      Else if nPos2=0 Then
          'Wscript.Echo Len(SourceStr)
          'Wscript.Echo nPos1
          'Wscript.Echo  Len(str1)
         retStr = Right( SourceStr, Len(SourceStr) - nPos1-Len(str1)+1 )
         strPath = strPath +"\" + trim(retStr)
         QueryStr = trim(retStr)
         'Wscript.Echo strPath
          CreateMyFolder(strPath)
       Else
         retStr = Mid( SourceStr, nPos1+Len(str1), nPos2 -nPos1-Len(str1))
         retStr1 = Right(SourceStr, Len(SourceStr)-nPos2-Len(str2)+1 )
         retStr1 = Replace( retStr1, "\", " or ")
         retStr1 = Replace( retStr1, "/", " or ")
         QueryStr = Null
         strPath = strPath + "\" + SubFolder + "\" + trim(retStr1) + "." + trim(retStr)
        'Wscript.Echo strPath
        CreateMyFile strPath,filesize
        End If
      End If
      'Wscript.Echo( nPos2)
      'Wscript.Echo( strPath)


    End Function

    Sub CreateMyFolder( strPath )
     
      Dim fso2, folder1
      Set fso2 = CreateObject("Scripting.FileSystemObject")
      If Not fso2.FolderExists(strPath) Then
         Set folder1 = fso2.CreateFolder(strPath)
      End If
      Set fso2=nothing
    End Sub

    Sub CreateMyFile( strPath, filesize)
      Dim fso3, file1
      Set fso3 = CreateObject("Scripting.FileSystemObject")
      If Not fso3.FileExists(strPath1) Then
         Set file1 = fso3.OpenTextFile( strPath, ForWriting , True) ' For Writing
         file1.WriteBlankLines filesize
         file1.Close
      End If
      Set fso3=nothing
    End Sub

    Sub Copy59Times(perFile)
       If CopyCheck=False Then
        Exit Sub
       End if

       Const copyFolder = "copy_data"
       'Const filesize = 512 '1kb
       Const nCount =59
       currentFolder = WorkingDir+"\"+CStr(perFile)
     Rem Wscript.Echo ("MakeSure your folder&file exist, Starting...")

       Dim fso, MyFile, testFolder
       Dim i, cFolder
        sFolder = currentFolder + "\" + sourceFolder

     Rem  sText = currentFolder + "\" + copyFolder+ Cstr(0) + "\file.txt"
      sText = currentFolder + "\file.txt"
      Rem Wscript.Echo (sText)


      Set fso = CreateObject("Scripting.FileSystemObject")
       for i=0 to nCount -1
          cFolder = currentFolder + "\" + copyFolder + CStr( i ) +"\"
          If fso.FolderExists ( cFolder + "\" ) Then
              fso.DeleteFolder( cFolder )
          End If
          fso.CreateFolder ( cFolder )

      'Set filetxt = fso.CreateTextFile(sText , True)
      'filetxt.WriteLine("STARTED AT")
      'filetxt.Close

      fso.CopyFolder sFolder,cFolder
       Next


      'Set filetxt = fso.OpenTextFile(sText , ForAppending , True)
      'filetxt.WriteLine("FINISHED AT")
      'filetxt.Close
    End Sub

    Public Function GetDriveLetter(keyWord)
     If keyWord="" Then
      keyWord="CF_Storage"
     End If
     Set bjFSO=CreateObject("Scripting.FileSystemObject")
     Set bjDrives=objFSO.Drives
     For Each objDrive In objDrives
      If objDrive.IsReady Then
       If objDrive.VolumeName=keyWord Then
         GetDriveLetter=objDrive
       End if
      End If
     Next
     Set bjFSO=nothing
    End Function

     

    Public Function Update_Result()
     Set fso=CreateObject("Scripting.FileSystemObject")
     Set Excel=CreateObject("Excel.Application")
     oExcel.Visible=True
     
     'Check if the test case is Exist
     If fso.FileExists(TestCase)Then
      Set bjWorkBook = oExcel.Workbooks.Open(TestCase)
      sheet_count=oExcel.Sheets.Count
      oExcel.Sheets.Item(sheet_count).Select
      Set bjSheet=oExcel.Sheets(sheet_count)
      With objSheet
      For i=start_Column+1 To  brand_Column
             If RegExpTest("8G",.Range(Chr(i)+CStr(record_PC))) Then
              CopyTime=Record_Time(8)
              off=offsite(8)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             ElseIf RegExpTest("1k",.Range(Chr(i)+CStr(record_PC))) Then
              copyTime=Record_Time(512)
              off=offsite(512)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             ElseIf RegExpTest("2k",.Range(Chr(i)+CStr(record_PC))) Then
              copyTime=Record_Time(1024)
              off=offsite(1024)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             ElseIf RegExpTest("4k",.Range(Chr(i)+CStr(record_PC))) Then
              copyTime=Record_Time(2048)
              off=offsite(2048)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             ElseIf RegExpTest("8k",.Range(Chr(i)+CStr(record_PC))) Then
              copyTime=Record_Time(4096)
              off=offsite(4096)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             ElseIf RegExpTest("16k",.Range(Chr(i)+CStr(record_PC))) Then
              copyTime=Record_Time(8192)
              off=offsite(8192)
              .Range(Chr(off+start_Column)+CStr(record_row)).value=copyTime
             Else
              MsgBox "Error, wrong case name"
             End if
            Next
            End with 
     End If
     oExcel.Save
     oExcel.Quit
     Set fso=nothing
    End Function

    Public Function offsite(perFile)
     Dim off
     Select Case perFile
      Case 8
       off=1
      Case 512
       off=2
      Case 1024
       off=3
      Case 2048
       off=4
      Case 4096
       off=5
      Case 8192
       off=6
     End Select
     offsite=off
    End Function

    Public Function Record_Time(perFile)
     Dim start_timer,end_timer
     Dim dir_org,dir_din
     Set bjfso=CreateObject("Scripting.FileSystemObject")
     If  perFile <> 8 then
      dir_org=WorkingDir+"\"+CStr(perFile)
      dir_din=CStr(CF_Storage)+"\" 
      If objfso.FolderExists(dir_din+CStr(perFile)+"\")Then
       objfso.DeleteFolder(dir_din+CStr(perFile))
      End if
     Else
      dir_org=WorkingDir+"\"+"8G"
      dir_din=CStr(CF_Storage)+"\"
      If objfso.FolderExists(dir_din+"8G"+"\")Then
       objfso.DeleteFolder(dir_din+"8G")
      End If
     End if
     start_timer_hour=Hour(Now)
     start_timer_minutes=Minute(Now)
     start_timer_seconds=Second(Now)
     Debug.WriteLine(Now)
     start_timer=CLng(start_timer_hour)*3600+CLng(start_timer_minutes)*60+CLng(start_timer_seconds)
     Debug.WriteLine(start_timer)
     objfso.CopyFolder dir_org, dir_din
     end_timer_hour=Hour(Now)
     end_timer_minutes=Minute(Now)
     end_timer_seconds=Second(Now)
     Debug.WriteLine(Now)
     end_timer=CLng(end_timer_hour)*3600+CLng(end_timer_minutes)*60+CLng(end_timer_seconds)
     Debug.WriteLine(end_timer)
     Record_Time=end_timer-start_timer
     Set bjfso=Nothing
    End Function

  • QTP 初起步II-调用其他应用程序

    2010-08-27 14:39:38

    Dim TestData_Location
    Dim TestData_Local
    Dim Login_Check
    TestData_Location="\\"
    TestData_Local="E:\Test\"
    TestData_Local_Check(TestData_Local)
    Login_Check=Log_in( "\\","admin","admin")
    CopyFile_Local TestData_Location,Login_Check
     

    Public Function TestData_Local_Check(TestData_Local)
       Set fso=CreateObject("Scripting.FileSystemObject")
       If fso.FolderExists(TestData_Local) Then
      fso.DeleteFolder(TestData_Local)
      fso.CreateFolder(TestData_Local)
     else
      fso.CreateFolder(TestData_Local)
       End If
       Set fso=nothing
    End Function
    Public Function  Log_in(ip,user,pw)
        Set bjShell=CreateObject("Wscript.Shell")
        objShell.Run ip
        Set bjShell=nothing
        wait(2)
        Set fso=CreateObject("Scripting.FileSystemObject")
       If fso.FileExists(TestData_Location) Then
         Log_in=True
        Else
         Log_in=False
        End If
    Set fso=nothing
    End Function
    Public Function CopyFile_Local(location,login_check)
       If  login_check Then
        Set fso=CreateObject("Scripting.FileSystemObject")
        fso.CopyFile location,TestData_Local
        Set fso=nothing
       End If
    End Function
    Public Function UnzipFile()
    End Function
     
     
     
     
     

     
  • QTP 初起步

    2010-08-17 14:47:06

     
    调用其他应用程序:
     
    Call Startup
    Function Startup
      SystemDrive=GetCDDrive("**")
     startup_command=SystemDrive&"\**"
        set pro = getobject("winmgmts:\\.").instancesof("Win32_Process")
     check_process=false
     For each ps in pro
      If UCase(ps.name)="aa.exe" or UCase(ps.name)="bb.exe" Then
       SystemUtil.CloseProcessByName(ps.name)
      End If
     Next
     SystemUtil.Run startup_command
     Do
      If Dialog("aa").Exist(2) Then
       Dialog("aa").CaptureBitmap "aa",True
      End If
      If Dialog("bb").Exist(2) Then
                Dialog("bb").CaptureBitmap "bb",True
       Dialog("bb").WinButton("c").Click
      End If
      If Dialog( "cc").Exist(5)Then
       Exit Do
      End If
     Loop
    End Function

    Function GetCDDrive(keyword)
       If keyword="" Then
        keywork="cc"
       End If
       Set bjFSO=CreateObject("Scripting.FileSystemObject")
       Set bjDrives=objFSO.Drives
       For each objDrive in objDrives
            If objDrive.IsReady and objDrive.DriveType=4Then
       If objDrive.VolumeName=keyword Then
        GetCDDrive=objDrive
        Exit For
       End If
      End If
       Next
       Set bjFSO=nothing
    End Function
  • 学习C#高级编程之XML

    2008-01-22 14:45:54

    验证XML文档的有效性---使用XMLReader

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.Xml;

    using System.Xml.Schema;

     

    namespace XMLValidatingTest1

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                XmlReaderSettings settings = new XmlReaderSettings();

                settings.Schemas.Add(null,@"D:\C#\books.xsd");

                settings.ValidationType = ValidationType.Schema;

    //C#高级编程第四版中的例子是错误的,XsdValidate 这个属性在.NET2.0中并不存在,这里//只需要使用ValidationType指定就可以

                settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(Settings_ValidationEventHandler);

                XmlReader xr = XmlReader.Create(@"D:\C#\books.xml",settings);

                while (xr.Read())

                {

                    if (xr.NodeType ==XmlNodeType.Text)

                    {

                        this.listBox1.Items.Add(xr.Value);

                    }

                }

            }

            private void Settings_ValidationEventHandler(object sender, ValidationEventArgs args)

            {

                MessageBox.Show(args.Message);

            }

        }

    }

     

  • 学习C#高级编程之XML

    2008-01-22 09:23:42

    处理XML

        System.Xml命名空间

     

    类名

    说明

    XMLReader

    抽象类,提供快速的没有缓存的XML数据,只向前的。

    XMLWriter

    抽象类,以流或文件的方式提供快速的,没有缓存的XML数据

    XMLTextReader

    扩展XMLReader, 提供访问XML数据的只读向前流。

    XMLTextWriter

    扩展XMLWriter, 快速生成只向前的XML 流。

    XMLNode

    抽象类,表示XML 文档的一个结点

    XMLDocument

    扩展XMLNode, 给出XML文档在内存中的树形表示。

    XMLDataDocument

    扩展XMLDataDocument, 可以从XML数据中加载文档, 也可以从ADO.NET中加载文档,允许放在一个视图中。

    XMLResolver

    抽象类, 分析基于XML的外部资源,例如DTD和模式引用,也可以用于处理<xsl:include><xls:import>

    XMLUrlResolver

    扩展XMLUrlResolver, URL解析外部资源。

     

        .NET中使用MSXML

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using MSXML2;

     

    namespace MSXMLTest

    {

        public partial class Form1 : Form

        {

            private DOMDocument60 doc;

            public Form1()

            {

                InitializeComponent();

            }

     

            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

            {

                string srch = this.listBox1.SelectedItem.ToString();

                IXMLDOMNode nd = doc.selectSingleNode("bookstore/book[@ISBN= '"+srch+"']");

    //选择所有ISBM=srch并且父结点等于bookstore的所有book接点

                MessageBox.Show(nd.text);

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                doc = new DOMDocument60();

                doc.load(@"D:\books.xml");

                IXMLDOMNodeList nodes;

                nodes = doc.selectNodes("bookstore/book");

                IXMLDOMNode node = nodes.nextNode();

                while (node != null)

                {

                    this.listBox1.Items.Add(node.attributes.getNamedItem("ISBN").text);

                    node = nodes.nextNode();

                }

            }

        }

    }

        使用System.XML

    XML Reader

     

     

     

     

     

    使用XmlTextReader

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.Xml;

     

    namespace XmlTextReaderTest

    {

        public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

     

            private void button1_Click(object sender, EventArgs e)

            {

                  System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(@"D:\books.xml");

                while (xr.Read())

                {

                    if (xr.NodeType == XmlNodeType.Text)

                        this.listBox1.Items.Add(xr.Value);

                }

     

            }

     

            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

            {

                string str = this.listBox1.SelectedItem.ToString();

                MessageBox.Show(str);

            }

        }

    }

     

  • 学习C# 高级编程之XML初起步

    2008-01-16 17:36:49

    XML DOM

          XML文档对象模型(XML Document Object Model)定义了一种访问和处理XML文档的标准方法。

    什么是DOM

    “W3C文档对象模型(DOM)是一个使程序和脚本有能力动态地访问和更新文档的内容、结构以及样式的平台和语言中立的接口。

    W3C DOM提供了一套标准的用于HTMLXML文档的对象,以及一个访问这些文档的标准接口。
       W3C DOM
    被分为不同的部分(核心、XMLHTML)以及不同的级别(DOM Level 1/2/3):

    什么是XML DOM?

    ·  XML DOM是针对XML的文档对象模型(Document Object Model

    ·  XML DOM独立于平台和语言

    ·  XML DOM定义了一套标准的用于XML的对象

    ·  XML DOM定义一种标准的访问XML文档的方法

    ·  XML DOM定义了一种标准的处理XML文档的方法

    ·  XML DOM是一个W3C标准

    DOMXML文档作为树结构来查看。所有的元素;它们所包含的文本以及它们的属性,可通过DOM树来进行访问。它们的内容可以被修改或删除,新内容也可被创建。元素、它们的文本以及它们的属性均被作为节点。

          C# XML 的命名空间

    类名

    说明

    XmlReader

    抽象的读取器类,提供快速,没有缓存的XML数据。XMLReader 是只读向前的。

    XmlWriter

    抽象的写入器,以流或文件的格式提供快速,没有缓存的XML数据。

    XmlTestReader

    扩展XMLReader,提供访问XML只度向前流。

    XmlTextWriter

    扩展XMLWriter,提供生成向前的XML流。

    其他比较重要的类

    类名

    说明

    XMLNode

    抽象类,表示XML中的一个结点。

    XMLDocument

    扩展XMLNode, 这是XML DOM的实现方式

    XMLDataDocument

    扩展XMLDocument, 即从XML数据中加载的文档,或从关系数据库中的文档。

    XMLResolver

    抽象类,分析基于XML的外部资源,例如DTD和模式引用,也可以用语处理<xsl:include><xsl:import>元素。

    XMLUrlResolver

    扩展XMLResolver, URL解析外部资源

     

          .Net 中使用MSXML

       //XPath is a language for finding information in an XML document. XPath is used to navigate t//hrough elements and attributes in an XML document.
    //Xpath
    是一种能够在XML文档中寻找信息的语言。它通过XML文档中的元素和属性来进行导//航。

    什么是 XPath?

    ·  XPath 使用路径表达式在 XML 文档中进行导航

    ·  XPath 包含一个标准函数库

    ·  XPath XSLT 中的主要元素

    ·  XPath 是一个 W3C 标准

    XPath 路径表达式

    XPath 使用路径表达式来选取 XML 文档中的节点或者节点集。这些路径表达式和我们在常规的电脑文件系统中看到的表达式非常相似。

    XPath 标准函数

    XPath 含有超过 100 个内建的函数。这些函数用于字符串值、数值,日期和时间比较、节点和 QName 处理、序列处理、逻辑值等等。

    XPath XSLT 中使用

    XPath XSLT 标准中的主要元素。如果没有 XPath 方面的知识,您就无法创建 XSLT 文档。

    您可以在我们的《XSLT 教程》中阅读更多的内容。

    XQuery XPointer 均构建于 XPath 表达式之上。XQuery 1.0 XPath 2.0 共享相同的数据模型,并支持相同的函数和运算符。

    XPath W3C 标准

    XPath 19991116 成为 W3C 标准。

    XPath 被设计供 XSLTXPointer 以及其他 XML 解析软件使用。

    您可以在我们的《W3C 教程

Open Toolbar