Re: Ignoring invalid namespace link in NSXMLDocument?
Christiaan Hofman <[email protected]>
| Newsgroups | gmane.comp.macosx.devel |
|---|---|
| Message-ID | <[email protected]> |
On Feb 9, 2010, at 19:26, Christiaan Hofman wrote: > I am trying to parse XML using NSXMLDocument and the -nodesForXPath:error: method of NSXMLNode. However, the XML I'm getting often has an invalid link in the xmlns attribute (for the name space) in a crucial element. The result apparently is that -nodesForXPath:error: does not find these nodes (or any of its children), even though I know they're there. As a case in point, when I remove the xmlns attribute, the method does return the nodes I'm looking for, though in practice of course I can't control the input. > > IMHO, I think it's a bug that it simply fails, and moreover silently (i.e. the error is not set), as the XML itself is perfectly valid. I don't think the result of parsing XML should depend on something that happens in some remote location. Note that I did NOT set the validation option when creating the XML document. > > Anyway, my question is whether someone knows a way for -nodesForXPath:error: to ignore such questionable errors, and simply parse the XML without further validation? I could not find any relevant optionss. > > Thanks, > Christiaan > Let me answer the question myself, after doing some more research. The problem was not really that the link in the xmlns was invalid (it's not supposed to be valid), but rather the fact that it's there. I now understand that when a namespace is declared using an xmlns attribute, the xpath query must also use precisely that namespace URI. I also understand that Cocoa does not provide any proper way to pass namespaces to an xpath query (there's no -nodesForXPath:usingNamespaces:error: method). Which basically means that Cocoa does not really support namespaces in xpath queries. Is my observation correct? Or did I overlook some API? Luckily I found a workaround that's sufficient for my purposes (but probably not for everybody's). Cocoa's xpath query engine actually use the namespaces that are declared (in the XML source) for the context node, which is the receiver of the Cocoa message. (Reading docs on xpath queries that's wrong.) But anyway, what I figure now I can do is to add any namespaces that may occur to the rootElement of the NSXMLDocument, and search for xpath queries twice: once with the namespace prefix, and if that fails (gives zero results) without the prefix. At least that works. If there is a better way, I would be interested to know. thanks, Christiaan