Question

I have an NSXMLElement that is a copy from somewhere else in my code. After it's been used, it no longer is connected to an NSXMLDocument. It's (what I believe to be) not linked to anything.

If I NSLog the NSXMLElement, I am given the contents. I can see it.

But, if I try to use nodesForXPath, it returns nothing. It's blank. It cannot find anything (unless I just search for *, in which case it returns everything with /t/t/n/t/t).

Now, if I make that NSXMLElement the root of a NEW NSXMLDocument, and then search the new document, I can search the XPath perfectly!

I am trying to understand the logic there. I have been reading the documentation, but I haven't found anything that explains what is happening here (or at least, I have no understood it if I did find it in the documentation).

I would really appreciate someone helping me understand exactly why this is happening, and whether or not I need to use this NSXMLDocument.

Here is my code:

(element is an NSXMLElement coming from an NSArray of stored NSXMLElements. They are copies from a document used in another method)

NSArray* scene = [element nodesForXPath:@"scene[1]" error:nil];
NSLog(@"scene: %@", [[scene objectAtIndex:0] stringValue]);

But if I do this, I get a result:

NSXMLDocument* docElement = [[NSXMLDocument alloc] initWithRootElement:element];
NSArray* scene = [docElement nodesForXPath:@"scene[1]" error:nil];
NSLog(@"scene: %@", [[scene objectAtIndex:0] stringValue]);
Was it helpful?

Solution

It's probably because the xpath context used by libxml2 holds a reference to the document. If there is no document, it probably doesn't know how to operate. The behavior if you search for * may just be a special-case because it knows it has to return everything so it doesn't even try to search.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top