开发者

NSXML add namespace to make XPath-queries work

I've got an issue where my XPath queries does not wo开发者_JAVA百科rk if an XMLNS attribute is defined in the document. I've figured out that this is probably because all elements is using the default XMLNS, while my XPath is not. However, I cannot find any suitable methods in NSXML (a common Objective C class-family for describing and parsing XML-documents) to solve the problem.

For example, the following code works fine if data does not contain a XMLNS. How to get the code to work if it does?

NSXMLDocument *xml = [[NSXMLDocument alloc] initWithData:data options:0 error:&error];   
NSArray *result = [xml nodesForXPath:@"/parent/child" error:&error];


I have just spent some time dealing with a similar issue (Google's KML files). Your problem is possibly due to the namespacing issue. When you set the namespace mappings, give the namespace a key, then prefix your selectors in your XPath expressions with that key followed by a colon (:). This solution uses CXMLDocuments and CXMLElements from the neat TouchXML library.

To start with a simple example, say your XML was:

<books xmlns="http://what.com/ever">
  <book>
    <title>Life of Pi</title>
  </book>
  <book>
    <title>Crime and Punishment</book>
  </book
</books>

You would select all the books with:

// So, assuming you've already got the data for the XML document
CXMLDocument* xmldoc = [[CXMLDocument alloc] initWithData:xmlDocData options:0 error:nil];
NSDictionary *namespaceMappings = [NSDictionary dictionaryWithObjectsAndKeys:@"http://what.com/ever", @"nskey", nil];
NSError *error = nil;
NSArray *bookElements = [xmldoc nodesForXPath:@"/nskey:books/nskey:book" namespaceMappings:mappings error:&error];

Note that you need to prefix every element, not just the one where the namespace is declared.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜