[译]XML格式的API数据的检索和解析.
By robot-v1.0
本文链接 https://www.kyfws.com/applications/retrieval-and-parsing-of-xml-formatted-api-data-zh/
版权声明 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
- 10 分钟阅读 - 4690 个词 阅读量 0[译]XML格式的API数据的检索和解析.
原文地址:https://www.codeproject.com/Articles/802478/Retrieval-and-Parsing-of-XML-Formatted-API-data
原文作者:CodeFate
译文由本站 robot-v1.0 翻译
前言
*Useful learning application to retrieve, parse and, format API XML documents to user friendly text. *
有用的学习应用程序,用于检索,解析API XML文档并将其格式化为用户友好的文本.
介绍(Introduction)
对于使用API XML数据的初学者来说,想知道如何接收和处理所接收的信息可能是一个令人困惑的时间.通过数百种获取信息的方法,它可以使新开发人员感到困惑.(For beginners working with API XML data, it can be a confusing time wondering how to receive and handle the information received. With hundreds of ways to get the information, it can add on to the confusion for the new developer.)
因此,我创建了一个可以被普遍理解和使用的简单应用程序.它在获取信息方面的方法非常简单.(Therefore, I created a simple application that can be understood and used universally. It is made to be extremely straightforward on its approach on how to get the information.)
了解守则(Understanding the Code)
选择一个非常基本的API(在本例中为获取定义),应用程序便能够获取,解析,格式化并输出为用户可读的信息.让我们找出如何做.(Picking a very basic API (in this case to get definitions), the application is able to get, parse, format, and output into user readable information. Let’s find out how to do that.)
API知识(API Knowhow)
在大多数情况下,连接到API服务时,该服务会要求您注册并申请获得(When connecting to an API service, most times, the service will ask you to sign up and apply to get an)API密钥(API Key).然后,大多数时候将要求将该键输入到查询中.在引用编程时,查询可能意味着许多不同的事物.最终,查询是您从API服务获取信息到应用程序的桥梁.(. That key will then, most times, be requested to be inputted into a query. A query can mean many different things when referring to programming. Ultimately, a query is your bridge to get information from the API service to your application.)
首先,看看是否可以(First, see if you can)获取API密钥(get an API key)到所需的API服务(如果需要).没有密钥,查询将失败. API密钥是您访问API服务的密钥.花时间开发应用程序是没有道理的,没有API密钥访问就没有用.(to the wanted API service (if required). Without the key the query will fail. The API key is your key to access the API service. There is no sense spending time developing an application, which is useless without that API key access.)
在此应用程序中,我使用了(In this application, I have used) STANDS4 Web服务:字典定义API(STANDS4 Web Services: Dictionary Definitions API) .单击底部的"在此处应用",然后按照说明获取使用该应用程序的API密钥.虽然没有必要,但强烈建议您这样做.(. Click “Apply here” at the bottom and follow the instructions to get the API key to use this application. While it is not necessary, it is highly recommended.)
STANDS4查询是一个(The STANDS4 query is a)要求网址(Request URL).请求URL是一种查询类型,它使用以下命令从网页获取信息(. A Request URL is a type of query that gets the information from a webpage using)参量(Parameters).(.)
这是请求网址:(Here is the Request URL:)
http://www.stands4.com/services/v2/defs.php
如果单击此按钮,将出现错误.其背后的原因是因为此请求URL需要参数.(If you click this you will get an error. The reason behind this is because this Request URL needs Parameters.)
这三个参数是:(The three Parameters are:)
- uid-您的API用户ID.(uid - Your API user ID.)
- tokenid-您的开发人员令牌ID.(tokenid - Your developer token ID.)
- 单词-您想要获得其定义的单词.(word - The word that you want to get your definition for.) 因此,请求网址示例如下所示:(So a sample Request URL will look like:)
http://www.stands4.com/services/v2/defs.php?uid=[youruidkey]&tokenid=[yourtokenidkey]&word=[wordtosearch]
这将是查询请求URL.该程序的真正实质.(This will be the query Request URL. The real meat of the program.)
了解XML数据(Understanding XML DATA)
现在,我们为您的查询提供了请求URL.那么我们该怎么办.我们在网络浏览器上对其进行测试,以查看其提供的信息类型.这将是你的(We now have our Request URL for our query. So what do we do. We test it out on our web browser to see what kind of information it gives. This will be your)样品响应(Sample Responce).样本响应可以采用许多不同的信息格式(文本,XM1,Json,图片等).本示例使用XML格式.(. A Sample Responce can be in many different information formats (text, XMl, Json, Pictures, ect). This example uses a XML format.)
样本响应如下所示:(A Sample Responce is like this:)
<?xml version="1.0" encoding="UTF-8"?>
<results>
<result>
<term>consistent, uniform</term>
<definition>the same throughout in structure or composition</definition>
<partofspeech>adj</partofspeech>
<example>bituminous coal is often treated as a consistent and homogeneous product</example>
</result>
</results>
在顶部,您将看到信息格式,这很重要,因为对于不同的格式,会有不同的处理方法.(At the top you will see the information format, this very important to understand being that for different formats there will be different processing methods.)
XML数据为树格式.一切都分支到另一件事.开始的分支是"结果",这称为(XML data is in a Tree format. Everything is branched off to another thing. The beginning branch is “results”, this is referred to as the)根(root).根里面可能有很多(. Inside the root there can be many)子根(sub-roots).此示例仅具有一个名为"结果"的子根.在您的子根目录中,您将获得(. This example only has one sub-root which is named “result.” Inside your sub-roots you will get)[R(r)刺激元素(esponce elements).这是您将在应用程序中使用的信息.(. This is the information that you will use in your application.)
示例响应元素为:(The example responce elements are:)
- 术语-字符串(term - String)
- 定义-字符串(definition - String)
- partofspeech-字符串(partofspeech - String)
- 示例-字符串(example - String) 注意这些元素.您稍后需要记住他们的名字.(Take note of these elements. You will need to remember their names later.)
请注意,虽然此XML树是此示例的设计,但有时在子根目录中可能存在子根目录.了解树是构建程序以从树中获取正确信息的唯一方法.(Please note that while this XML tree is the design of this example, some times there can be sub-roots inside of sub-roots. Understanding the tree is the only way to build a program to get the correct information from the tree.)
使用代码(Using the code)
现在您已经了解了什么是API,API密钥有多重要以及基本的XML数据结构使您可以编写程序.(Now that you understand what API’s are, how important API keys are, and the basic XML data structure lets make a program.)
如果您认为合适,我将把所有设计和基本项目创建留给您.(If you see fit, I will leave all the design and basic project creation up to you.)
获取查询(Getting a Query)
要获取查询,将需要进行(To get a Query will will need to make a) WebRequest
.的(. The) WebRequest
参考在System.Net中.(reference is in System.Net.)
您需要使用"(You will need to add that reference in the top of the application using the “) using
“命令.(” command.)
using System.Net;
同样在该类下,我们将需要使应用程序范围的变量.虽然可以将变量包含在空隙中,但是如果要重用变量,最好始终将其保留在内存中.使它们成为应用程序范围的变量可以加快查询的响应时间.(Also under the class we will need to make an application wide variable. While you can include variables into the voids, if you are reusing variables it’s better to have them always in memory. Making them a application wide variable speeds up the responce time for Querys.)
在公众偏下阶级下(Under the public partial class) [yourformname]
:表格括号请输入:(: Form bracket please enter:)
WebResponse webResponse;
现在,我们需要在私有的void上附加一个字符串(这样我们就可以获得搜索词).(Now we need to make a private void with a string attached to it (so we can get the search word).)
private void Query(string word)
{
}
在新的私有void的括号中,添加以下代码:(In the brackets of your new private void add in this code:)
var webRequest = WebRequest.Create([Request URL]);
这将使查询变量.我们可以用它来做各种各样的事情.(This will make a variable for the Query. We can do all sorts of things with this.)
现在让我们尝试获取查询.关键字是try,如果查询失败,我们将无法获得任何可以使用的内容.因此,在那里存在try and catch命令很重要.(Let’s now try to get the Query. The key word is try, if the Query is invaild we will not get anything we can work with. Thus is important that a try and catch command is there.)
try
{
webResponse = webRequest.GetResponse();
}
catch (WebException)
{
textbox.Text = "No internet connection.";
return;
}
catch (Exception e)
{
textbox.Text = "Something went wrong." + e;
return;
}
这将从API服务获得响应.如果用户未连接到互联网,它将调用一个(This will get a responce from the API service. If the user is not connected to internet it will invoke a) WebException
,并显示一条错误消息"没有互联网连接”.如果出了点问题,但与互联网无关,它将发出一条错误消息,指出"出了点问题".(, making an error message saying “No internet connection.” If something goes wrong, but is not about the internet, it will do an error message saying “Something went wrong” with the Exception.)
接下来,我们将连接到API服务:(Next we will connect to the API service:)
var appCastStream = webResponse.GetResponseStream();
这使用请求URL从API服务中打开了一个蒸汽.(This opens up a steam from the API service using the Request URL.)
现在,如果请求URL无效且未返回任何内容,我们可能会遇到问题.这可以检查它是否不为空:(Now if the Request URL is invaild and returns nothing we might have a problem. Thus lets check if it is not null:)
if (appCastStream != null)
{
receivedAppCastDocument.Load(appCastStream);
}
else
{
textbox.Text = "API is down. Please try again later";
return;
}
如果我们从查询中获得信息,它将把信息加载到我们的应用程序中.(If we got information from the Query it will load the information into our application.)
ReceivedAppCastDocument
是System.XML引用.确保将其添加到您的使用列表中:(is a System.XML reference. Make sure to add that to your using list:)
using System.Xml;
很好!现在,我们有了来自查询的信息!(Great Job! We now have information from the Query!)
解析中(Parsing)
剩下要做的唯一一件事就是从查询中获取信息.这种检索动作称为解析.(The only thing left to do is get the information from the Query. This retieval act is called parsing.) ReceivedAppCastDocument
使其非常容易做到.(makes it extreamly easy to do.)
这也是在浏览器中打开示例请求的地方.(This is also where having a sample request open on your browser comes in handy.)
现在,我们将记住示例请求XML树的结构.这是为了建立索引来解析信息.它会告诉计算机在哪里可以找到信息以及如何处理信息.(We will now remember the sample request XML tree’s structure. This is to build an index to parse the information. It will tell the computer where exactly to find the information and what to do with it.)
var result = receivedAppCastDocument.SelectNodes("results/result");
ReceivedAppCastDocument.SelectNodes
使(makes an) Xpath(Xpath) XML.这将建立索引. “结果/结果"是到达响应元素的树.首先具有根,然后再具有子根.如果您具有不同的命名根目录和子根目录,请相应地进行更改.请注意,从这里开始,字母外壳必须是准确的.(of the XML. This builds the index. “results/result” is the tree to get to the responce elements. First with the root then to the sub-root. If you have different named root and sub-roots please change it accordingly. Please note that LETTER-casing needs to be exact from here on in.)
现在让我们检查是否有任何响应元素:(Let’s now check if we have any responce elements:)
if (result != null)
{
}
这将检查结果是否为空.如果不是,则继续进行.这很酷,我们可以添加一个”(This checks if result is null. If it isn’t then it carries on. What’s cool about this, is that we can add a “) else
声明,如果我们没有回应元素,请采取措施.(” statement and do something if we have no responce elements.)
现在这变得复杂了.现在,我们将从响应元素中选择并获取信息,但是,如果有很多带有响应元素的子根,我们要确保不覆盖它们.听起来复杂吗?但是解决方案就像发出一个foreach命令一样简单.(This is now where it gets complicated. We will now select and get information from the responce elements, however if there is many sub-roots with responce elements we want to make sure that we do not overwrite them. Sounds complicated? But the solution is as simple as making a foreach command.)
foreach (XmlNode item in result)
{
var term = item.SelectSingleNode("term").InnerText;
var partofspeech = item.SelectSingleNode("partofspeech").InnerText;
var definition = item.SelectSingleNode("definition").InnerText;
var example = item.SelectSingleNode("example").InnerText;
}
如您所见,将变量分配给响应元素并不难.此foreach命令将创建一个新的"项目",可以对其进行索引以获取响应元素的InnerText.由于这是一个foreach命令,因此它为每个单个子根执行此操作.(As you can see assigning a variable to the responce elements is not hard. This foreach command makes a new “item” that can be indexed to get the InnerText of the responce element. Being that it’s a foreach command it does this for every single sub-root.)
现在,您可以从"查询in字符串变量"中获取信息,可以按照自己的意愿进行操作.我总是建议检查变量是否有效/不为空.要在字符串上执行此操作,您需要创建一个if语句.(Now you have the information from the Query in string variable to do as you please. I always recommend checking to see if the variables are valid/not empty. To do this on a string you need to make a if statement.)
if (term != "")
{
}
else
{
}
这可以抵消格式中的任何空白点.(This counteracts any blank spots in your formating.)
结论(Conclusion)
如果您确实阅读了所有内容,那么恭喜!希望您学到了很多.(If you actually read all that, congratulations! I hope that you have learned a lot.)
测试随附的样本源.希望它可以帮助您理解.(Test out the sample source included. It hopefully it helps your understanding.)
干杯!(Cheers!)
如果您喜欢它,请确保给我价.(If you liked it make sure that you give me a rate.)
附言请记住,并非每个Xml文档都是相同的,有些可能比此示例复杂得多.如果您遇到API格式方面的问题,获得答案的最佳方法是与该API服务的支持人员联系.(Ps. Remember that not every Xml document is the same, some may be much more complex then this example. If you run into a problem with a API formating the best way to get answers is contacting support for that API service.)
许可
本文以及所有相关的源代码和文件均已获得The Code Project Open License (CPOL)的许可。
XML C# VS2013 API application 新闻 翻译