(Kiss) XML xpath and default namespace

I am working on an iPhone project that needs to parse some xml. Xml may or may not include a default namespace. I need to know how to parse xml if it uses the default namespace. Since I need to read xml, I tend to use KissXML, but I'm open to suggestions.

This is my code:

NSString *content = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
    pathForResource:@"bookstore" ofType:@"xml"] encoding:NSUTF8StringEncoding error:nil];

DDXMLDocument *theDocument = [[DDXMLDocument alloc] initWithXMLString:content options:0 error:nil];

NSArray *results = [theDocument nodesForXPath:@"//book" error:nil];
NSLog(@"%d", [results count]);

It works as expected in this xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
</book>
</bookstore>

But when xml has a namespace, for example, it stops working:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore xmlns="[INSERT RANDOM NAMESPACE]">
<book category="COOKING">
  <title lang="en">Everyday Italian</title>
</book>
<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
</book>
</bookstore>

Of course, I could just process the string and remove xmlns, although this seems like an ugly hack. What is the right way to handle this?

+3
source share
2 answers

:

XPath, , ; , , . , , , KissXML:

namespace-uri(/*)

, , XML uri.

:

, KissXML XPath 1.0. ( ) :

//*[local-name(.) = 'book']

XPath 2.0, , :

//*:book
+6

KissXML "" , NSXML . . , .

found , , XPath. - :

    DDXMLNode *defaultNamespace = [document.rootElement namespaceForPrefix:@""];
    defaultNamespace.name = @"default";
    NSArray *xmlNodes = [[document rootElement] nodesForXPath:@"//default:foo/default:bar" error:nil];

, . , , .

+4

All Articles