且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用NSXMLParser解析基本XML文件?

更新时间:2022-05-04 08:20:12

NSXMLParser 遇到XML标签时,将调用委托方法 parser:didStartElement:namespaceURI:qualifiedName:attributes: ;你可能只需要在这里使用 elementName 变量。然后,XML解析器读取标记中的字符,并与内容一起调用 parser:foundCharacters:。最后 parser:didEndElement:namespaceURI:qualifiedName 被调用。

The first thing that happens when the NSXMLParser encounters an XML tag is that the delegate method parser:didStartElement:namespaceURI:qualifiedName:attributes: is called; you'll probably only need to use the elementName variable here. Then, the XML parser reads the characters in the tag and calls parser:foundCharacters: with the contents. Finally parser:didEndElement:namespaceURI:qualifiedName is called.

我采取的方法,在 SeismicXML 考试中使用以下方法:

The approach that I've taken, as Apple uses in the SeismicXML examlple, is to use the methods as follows:


  1. :didStartElement:namespaceURI:qualifiedName:attributes:,将元素名称的字符串与已知值进行比较,看看它是否是您关心的字符串。如果是这样,然后设置一个实例变量( NSMutableString ;我将其称为 contentOfCurrentXMLProperty )为空字符串。否则将其设置为 nil

  2. parser:foundCharacters: contentOfCurrentXMLProperty 找到的字符。

  3. 解析器:didEndElement:namespaceURI:qualifiedName ,将 contentofCurrentXMLProperty 的值赋给任何适当的变量。

  1. In parser:didStartElement:namespaceURI:qualifiedName:attributes:, compare the string of the element name to a known value to see if it's a string you care about. If so, then set an instance variable (an NSMutableString; I'll call it contentOfCurrentXMLProperty) to an empty string. Otherwise set it to nil.
  2. In parser:foundCharacters:, append the found characters to contentOfCurrentXMLProperty.
  3. In parser:didEndElement:namespaceURI:qualifiedName, assign the value of contentofCurrentXMLProperty to whatever the appropriate variable is.

有关详细信息,请参阅 SeismicXML 示例。

See the SeismicXML example for more information.

有关您的特定情况的几个问题:首先,由于XML解析器只返回字符串需要将 status 的字符串转换为整数(或您使用的任何数据类型)。

A couple of things about your specific case: first, since the XML parser only returns strings, you'll need to convert the string to an integer (or whatever data type you're using) for status.

第二,因为你只需要记录的第一个值,在 parser:didStartElement:... 设置 BOOL ,用于标记您之前是否已经看到记录标记,如果是,则设置 contentOfCurrentXMLProperty nil

Second, since you only want the first value for record, in parser:didStartElement:... I'd set up a BOOL that flags whether you've already seen a record tag before and, if so, set contentOfCurrentXMLProperty to nil.