提取信息。从XML到可可 [英] Extracting info. from XML into Cocoa
问题描述
我试图解析XML以提取某些变量的值。这里有一个例子:
I am trying to parse an XML to extract values of certain variables. Here's an example:
<?xml version='1.0'?>
<Main xmlns='http://www.abc.uk' version='1.0' name='full'>
<child1 version='2.0'>
<value1> xyz </value1>
<userinfo>
<name> joe </name>
<pass> joepass </pass>
</userinfo>
</child1>
</Root>
问题:
如何提取要显示的xyz值?
如何提取'joe'和'joepass'来显示?
Question: How do I extract the 'xyz' value to display ? How do I extract 'joe' and 'joepass' to display ?
根据我的理解,child1是属性为version的根。 'value1'和'userinfo'都是元素。在Cocoa中,我如何显示这些值?我可以做一个[child elementsForName:@userinfo,它显示所有的值。我需要特别提取'joe'和'joepass'。
From my understanding, child1 is the root with attribute 'version'. 'value1' and 'userinfo' are both elements. In Cocoa, how would I display these values ? I can do a [child elementsForName:@"userinfo" and it displays all the values. I need to specifically extract 'joe' and 'joepass'. Thanks.
推荐答案
如何将'xyz'值提取到
显示?如何提取'joe'和
'joepass'显示?
How do I extract the 'xyz' value to display ? How do I extract 'joe' and 'joepass' to display ?
这假设你在 NSString
中有你的XML:
With something like this. This assumes you have your XML in an NSString
:
NSXMLDocument* xmlDoc;
NSError* error = nil;
NSUInteger options = NSXMLNodePreserveWhitespace|NSXMLDocumentTidyXML;
xmlDoc = [[NSXMLDocument alloc] initWithXMLString:xmlString
options:options
error:&error];
if (!error)
{
NSArray* value1Nodes = [xmlDoc nodesForXPath:@".//Main/value1" error:&error];
if (!error)
{
NSXMLNode* value1node = [value1Nodes objectAtIndex:0];
NSString* value1 = [value1node stringValue];
// .. do something with value1
}
NSArray* userInfoNodes = [xmlDoc nodesForXPath:@".//Main/userinfo" error:&error];
if (!error)
{
for (NSXMLNode* userInfoNode in userInfoNodes)
{
NSXMLNode* nameNode = [[userInfoNode nodesForXPath:@"./name" error:&error] objectAtIndex:0];
NSXMLNode* passNode = [[userInfoNode nodesForXPath:@"./pass" error:&error] objectAtIndex:0];
NSString* name = [nameNode stringValue];
NSString* pass = [passNode stringValue];
// .. do something with name and pass
}
}
有关详情,请参阅Apple的树基于XML的编程指南。
See more details in Apple's Tree-Based XML Programming Guide.
根据我的理解,child1是属性为version的
根。
'value1'和'userinfo'都是
元素。
From my understanding, child1 is the root with attribute 'version'. 'value1' and 'userinfo' are both elements.
/ code>是此XML文档中的根节点,不是
child1
。
这篇关于提取信息。从XML到可可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!