0

我有一个带有多个入口节点的 XML 文件:

<entry>
    <published>2013-12-19T13:30:20-05:00</published>
    <title>This is a title</title>
    <content type="html">This is the content</content>
    <author>
        <name>Valentina</name>
    </author>
</entry>

我正在尝试使用 XPath 解析它(用于学习目的),但我似乎无法让它工作。我有以下代码:

        NSData* xmlData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:link]];
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:nil];

        NSArray* entries = [document.rootElement elementsForName:@"entry"];
        for(GDataXMLElement* element in entries)
        {
            published = [element nodesForXPath:@"/entry/published" error:nil][0];
        }

index 0 beyond bounds for empty array尝试获取published节点文本时总是出错。我尝试了不同的方法,但不知道什么是正确的方法。
Entries 数组包含 10 个入口节点。

4

1 回答 1

1

XPath 是从当前上下文评估的,当前上下文已经是一个<entry/>元素。将 XPath 表达式更改./publishedpublished.

published = [element nodesForXPath:@"published" error:nil][0];

但是,如果您只想查询子节点,为什么还要使用 XPath?

published = [element elementsForName:@"published"][0];
于 2013-12-19T20:01:07.037 回答