2008年12月31日水曜日

XPathをためす

こちら(XPath Syntax)を参考に.

  NSXMLDocument* document= [NSXMLNode document];
[document setVersion:@"1.0"];
[document setCharacterEncoding:@"ISO-8859-1"];

NSXMLElement* bookstore= [NSXMLNode elementWithName:@"bookstore"];
[document setRootElement:bookstore];
{
NSXMLElement* book= [NSXMLNode elementWithName:@"book"];
[bookstore addChild:book];
{
NSXMLElement* title= [NSXMLNode elementWithName:@"title"];
[book addChild:title];
[title addAttribute:[NSXMLNode attributeWithName:@"lang"
stringValue:@"eng"]];
[title addChild:[NSXMLNode textWithStringValue:@"Harry Potter"]];
}
{
NSXMLElement* price= [NSXMLNode elementWithName:@"price"];
[book addChild:price];
[price addChild:[NSXMLNode textWithStringValue:@"29.99"]];
}
}
{
NSXMLElement* book= [NSXMLNode elementWithName:@"book"];
[bookstore addChild:book];
{
NSXMLElement* title= [NSXMLNode elementWithName:@"title"];
[book addChild:title];
[title addAttribute:[NSXMLNode attributeWithName:@"lang"
stringValue:@"eng"]];
[title addChild:[NSXMLNode textWithStringValue:@"Learning XML"]];
}
{
NSXMLElement* price= [NSXMLNode elementWithName:@"price"];
[book addChild:price];
[price addChild:[NSXMLNode textWithStringValue:@"39.95"]];
}
}

NSString* output= [document XMLStringWithOptions:(NSXMLNodePrettyPrint|NSXMLNodeCompactEmptyElement)];
NSLog(@"%@", output);

NSArray *nodes= [bookstore nodesForXPath:@"/bookstore/book[price>35.00]/title" error:NULL];
NSLog(@"%d", [nodes count]);
int i;
for(i= 0;i<[nodes count];i++) {
NSLog(@"%@", [[nodes objectAtIndex:i] XMLString]);
}


結果
> <?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book>
<title lang="eng">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="eng">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>
> 1
> <title lang="eng">Learning XML</title>

0 件のコメント: