XML文件读取的方法 - 极悦
专注Java教育14年 全国咨询/投诉热线:444-1124-454
极悦LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 XML文件读取的方法

XML文件读取的方法

更新时间:2022-01-21 10:48:37 来源:极悦 浏览1752次

本课将向您展示如何加载 XML 文件并访问数据以在您的应用程序中使用。XML 文件对于存储首选项设置、使用 Web 以及需要与其他程序共享数据的情况非常有用。

LiveCode 提供了一个功能完善的库来处理 XML 文件,这可能需要一点时间来适应,但使用起来非常简单。

使用按钮和字段创建堆栈

我们首先创建一个堆栈并将一个按钮和一个字段拖到它上面。该按钮将包含我们用于读取 XML 文件的 LiveCode 代码。该字段将包含从文件中读取的结果数据,将字段名称设置为“信息”。将此堆栈保存在您的桌面上。

创建一个 XML 文件以用作示例

使用 Windows 上的记事本或 Mac OS X 上的 TextEdit 创建示例首选项 XML 文件。该文件应该是纯文本。在桌面上将文件另存为“Preferences.xml”。XML 数据如下所示:

<preferences>
  <textColor>blue</textColor>
  <textSize>16</textSize>
  <introMessage size="18">Welcome guest, please click the button below to log in</introMessage>
  <recentDocuments>
    <recentDocument>C:/Documents and Settings/Administrator/Documents/DraftReport.txt</recentDocument>
    <recentDocument>C:/Reports/2009Final.txt</recentDocument>
    <recentDocument>C:/Documents and Settings/Administrator/Desktop/Temp.txt</recentDocument>
  </recentDocuments>
</preferences>

告诉按钮在用户单击时加载文件

通过选择它来编辑按钮的脚本,然后单击主菜单栏中的“脚本”按钮。对于本例,我们将加载一个包含应用程序首选项的 XML 文件。

使用以下代码开始脚本:

1.点击按钮时,加载首选项并将它们放入字段中

on mouseUp
   loadPreferences
end mouseUp

2.加载首选项文件

加载首选项文件有两个部分。第一部分是将文件读入内存并创建一个 XML“树”。第二部分是处理树并从中提取数据。

此函数读取 XML 文件,并返回树。树表示为一个数字,实际的树结构和数据由 LiveCode 管理,因此我们无需担心。

command loadPreferences
   local tTree
   put readPreferencesToXMLTree() into tTree
   if tTree is empty then
      exit loadPreferences
   end if 
   # Read the preferences we require from the tree and display them.
   processPreferencesTree tTree
 
   # Close the XML tree. 
   # This will free up the memory that the tree was using and prevent our application
   # using more memory than it needs or "leaking" memory by creating multiple trees
   # without closing any of them.
   revXMLDeleteTree tTree
end loadPreferences

请注意,这段代码还没有做任何事情,因为我们还没有实现函数 readPreferencesToXMLTree 和命令 processPreferencesTree。

从磁盘读取 XML 文件

接下来,我们实现一个函数来读取 XML。这分两步完成,首先将文件读入一个变量,就像任何其他文本文件一样,其次,从文件中创建一个 XML“树”。这棵树允许我们轻松地操作 XML 数据。

添加代码以读取 XML 文件,如下所示。

private function readPreferencesToXMLTree
   # Find the XML file on disk. 
   # This is for now assumed to be in the same location as the stack / application.
   # Note that we restore the itemDelimiter to comma (its default value) afterwards.           	
   # This is not essential but its good practice to avoid tricky bugs 
   # that can arise due to unexpected delimiter values.
   set the itemDelimiter to slash
   local tPreferencesFile
   put item 1 to -2 of the effective filename of this stack & "/Preferences.xml" into tPreferencesFile
   set the itemDelimiter to comma 
   # Read the preferences data from the file into a variable. 
   # Always check for the result when reading files
   # as its possible that the file may have been deleted or moved.
   local tPreferencesData, tResult
   put url ("file:" & tPreferencesFile) into tPreferencesData
   put the result into tResult
   if tResult is not empty then
      answer error "Failed to read preferences file at location: " & tPreferencesFile
      return empty
   end if 
   # Create the XML "tree" from the data, 
   # checking to make sure that the file has loaded properly.
   # The revCreateXMLTree function will return a number 
   # (the tree's "handle" or "id") if it succeeds,
   # otherwise it will return a message saying why it failed.
   local tTree
   put revXMLCreateTree(tPreferencesData, false, true, false) into tTree
   if tTree is not an integer then
      answer error "Failed to process preferences file with error: " & tTree
      return empty
   end if 
   return tTree
end readPreferencesToXMLTree

从 XML 文件中提取信息并将其显示在字段中

一旦我们有了 XML 树,最后一步是使用 LiveCode 的 XML 库从中获取所需的信息。我们使用对 XML 库的一系列调用来从树中提取每条信息。

private command processPreferencesTree pTree
   # Extract the text color and text size preferences. 
   # These are simple nodes in the XML file,
   # we can get what is inside them using the revXMLNodeContents function
   # This function will return a string beginning with "xmlerr," 
   # if it fails, but we don't check this 
   # here as we created the file and we know it won't fail.
   local tTextColor
   put revXMLNodeContents(pTree, "preferences/textColor") into tTextColor 
   local tTextSize
   put revXMLNodeContents(pTree, "preferences/textSize") into tTextSize 
   # Extract the introductory message preference. 
   # This node has an attribute. We extract the contents and the 
   # attribute in two separate calls. 
   # The function revXMLAttribute allows us to read attributes from XML files,
   # its exactly the same as revXMLNodeContents, 
   # except that you also need to tell it which attribute you want.
   local tIntroMessage
   put revXMLNodeContents(pTree, "preferences/introMessage") into tIntroMessage 
   local tIntroMessageSize
   put revXMLAttribute(pTree, "preferences/introMessage", "size") into tIntroMessageSize 
   # Extract the recent documents list. 
   # This is a nested list of nodes, which could have any number of items.
   # First, we get a list of the recent documents, then we can loop 
   # through them and get each one in turn.
   # The revXMLChildNames function is useful for returning a list of nodes like this.  
   # The last parameter is important as it tells the function to return a unique
   # specifier for each node, allowing us to access them correctly. This will
   # look something like:
   #	recentDocument[1]
   #	recentDocument[2]
   #	recentDocument[3]
   local tRecentDocuments
   put revXMLChildNames(pTree, "preferences/recentDocuments", return, "recentDocument", true) into tRecentDocuments 
   # To get each document, we just use revXMLNodeContents again. 
   # However here we concatentate the name of each node
   # with the path that all recent document nodes have in common, 
   # to get the complete path.
   local tListOfRecentDocuments
   repeat for each line tRecentDocument in tRecentDocuments
      put revXMLNodeContents(pTree, "preferences/recentDocuments/" & tRecentDocument) & return after tListOfRecentDocuments
   end repeat
   delete the last char of tListOfRecentDocuments 
   # Now we output what we read from the file to see if it worked.
   local tOutput
   put "Text Color = " & tTextColor & return after tOutput
   put "Text Size = " & tTextSize & return after tOutput
   put return after tOutput
   put "Introductory Message (size: " & tIntroMessageSize & ") = " & return after tOutput
   put tIntroMessage & return & return after tOutput
   put "Recent Documents = " & return after tOutput
   put tListOfRecentDocuments after tOutput
   set the text of field "Information" to tOutput
end processPreferencesTree

测试

测试堆栈切换到运行模式并单击按钮。

以上就是关于“XML文件读取的方法”介绍,大家如果想了解更多相关知识,不妨来关注一下极悦的Java视频,里面的课程内容详细,通俗易懂,适合小白学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>