从网站抓取 XML 文件数据
只是想知道获取以下数据并解析它的最佳方法是什么。
这是我想要提取的一些数据的示例。
<?xml version="1.0" encoding="UTF-8" ?>
<eveapi version="2">
<currentTime>2010-11-19 19:23:44</currentTime>
<result>
<rowset name="characters" key="characterID" columns="name,characterID,corporationName,corporationID">
<row name="jennyhills" characterID="90052591" corporationName="Imperial Academy" corporationID="1000166" />
</rowset>
</result>
<cachedUntil>2010-11-19 20:20:44</cachedUntil>
</eveapi>
我看过一些关于如何解析 XML
数据的示例,但它们都是基于 if 语句,并且有大量的硬编码,是否有更通用的方法来执行此操作?
Just wondering what would be the best way to grab the following data and parse it.
Here's an example of some the data I want to pull.
<?xml version="1.0" encoding="UTF-8" ?>
<eveapi version="2">
<currentTime>2010-11-19 19:23:44</currentTime>
<result>
<rowset name="characters" key="characterID" columns="name,characterID,corporationName,corporationID">
<row name="jennyhills" characterID="90052591" corporationName="Imperial Academy" corporationID="1000166" />
</rowset>
</result>
<cachedUntil>2010-11-19 20:20:44</cachedUntil>
</eveapi>
I've seen some examples on how to parse XML
data but they are all based on if statements and that's a lot of hard coding is there a more generic way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解析器是硬编码的,这就是它们的工作方式。您只能检查某个标签是否与某个模式匹配,然后决定要做什么。特别是对于像您这样的简单文档,这绝对没有问题。
如果您要解析不止一种类型的文档,那么我建议您阅读此
Parsers are quite hardcoded that's the way they work. You can only check if a certain tag matches a certain pattern and then decide what to do. Especially for simple documents like yours that is absolutely no problem.
If you have more than one type of document to parse then I recommend reading this SO answer.
从字面意思来看,“解析”很容易。解析是获取文本字符串(在您的例子中,来自 http 响应)并将其转换为数据结构(例如 XML 文档树)的过程。该过程由 XML 解析器为您处理,您通常不需要担心它。
您面临的部分是如何从解析的 XML 文档中查询数据,对吗?最简单的方法很大程度上取决于您需要如何处理数据。但是 XPath 是一种很好的选择方法数据,没有大量冗长的 if 语句和 get-child 函数调用。
另请参阅有关在 Android 中使用 XPath 的问题。
The "parsing", taking the term literally, is easy. Parsing is the process of taking a text string (in your case, from an http response) and turning it into a data structure such as an XML document tree. That process is handled for you by an XML parser, and you typically don't need to worry about it.
The part you're facing is how to query data from the parsed XML document, right? The easiest way to depends greatly on what you need to do with the data. But XPath is a good way to select data without a lot of verbose if statements and get-child function calls.
See also this question on using XPath in Android.