0

我的 Web 服务中有以下格式的 XML。

<xml>
    <Menu>
        <pair>
            <MenuCategory shortname="Starters Menu" description_en="hgfhghgh" image="Small.jpg" description_fr="" description_ge="" description_it="" description_sp="" description_ch="">
                <MenuItems>
                    <menuItem price="666" image="060649XSmall.jpg" shortname="kandan" description_en="kandan" description_fr="" description_ge="" description_it="" description_sp="" description_ch=""/>
                    <menuItem price="250" image="3.jpg" shortname="Vegetable Soups" description_en="Vegetable Soups" description_fr="" description_ge="" description_it="" description_sp="" description_ch=""/>
                    <menuItem price="52" image="3.jpg" shortname="Mixed Starters" description_en="Mixed Starters" description_fr="" description_ge="" description_it="" description_sp="" description_ch=""/>
                    <menuItem price="45" image="14.jpg" shortname="Pumpkin soup" description_en="Pumpkin soup" description_fr="" description_ge="" description_it="" description_sp="" description_ch=""/>
                    <menuItem price="15" image="15.jpg" shortname="Almondrolledgoatsche" description_en="Almondrolledgoatsche" description_fr="" description_ge="" description_it="" description_sp="" description_ch=""/>
                </MenuItems>
            </MenuCategory>
        </pair>
    </Menu>
</xml>

我尝试使用 TBXML 从我的 web 服务中解析这个 XML。但是,还没有得到我的输出,

TBXML *XML = [[TBXML alloc]initWithURL:[NSURL URLWithString:urlString]];
TBXMLElement *rootXML = XML.rootXMLElement;
TBXMLElement *e = [TBXML childElementNamed:@"MenuItems" parentElement:rootXML];
NSString *woeid = [TBXML textForElement:e->firstChild];
NSLog(@"Woeid - %@", woeid);    

它简单地抛出EXEC_BAD_ACCESS错误。我只需要将此 xml 解析为我的NSMutableArray有很多与此相关的示例。但是,不知道哪一个适合我的要求。有没有人以这种格式工作过?知道如何实现这一目标吗?

4

5 回答 5

1

我认为以下代码可能会对您有所帮助。并且您已经做出了选择 TBXML 进行 xml 解析的不错选择。

在 .h 文件中

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSXMLParserDelegate>

 {
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError **errorPointer;
}

+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;

@end

在 .m 文件中

NSString *const kXMLReaderTextNodeKey = @"text";

@interface ViewController ()

- (id)initWithError:(NSError **)error;
- (NSDictionary *)objectWithData:(NSData *)data;

@end

@implementation ViewController

- (void)viewDidLoad{


NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"Your URL Here"]];

NSError *parseError = nil;
NSDictionary *xmlDictionary = [ViewController dictionaryForXMLData:data error:&parseError];    // Print the dictionary

NSLog(@"%@",xmlDictionary);



}


+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{   
ViewController *reader = [[ViewController alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithData:data];
[reader release];
return rootDictionary;
}

 + (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{ 
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [ViewController dictionaryForXMLData:data error:error];
}


- (id)initWithError:(NSError **)error
{
if (self = [super init])
{
    errorPointer = error;
}
return self;
}

- (void)dealloc
{
[dictionaryStack release];
[textInProgress release];
[super dealloc];
}

- (NSDictionary *)objectWithData:(NSData *)data
{
// Clear out any old data
[dictionaryStack release];
[textInProgress release];

dictionaryStack = [[NSMutableArray alloc] init];
textInProgress = [[NSMutableString alloc] init];

// Initialize the stack with a fresh dictionary
[dictionaryStack addObject:[NSMutableDictionary dictionary]];

// Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
BOOL success = [parser parse];

// Return the stack’s root dictionary on success
if (success)
{
    NSDictionary *resultDict = [dictionaryStack objectAtIndex:0];
    return resultDict;
}

return nil;
}

#pragma mark -
#pragma mark NSXMLParserDelegate methods

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// Get the dictionary for the current level in the stack
NSMutableDictionary *parentDict = [dictionaryStack lastObject];

// Create the child dictionary for the new element, and initilaize it with the attributes
NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
[childDict addEntriesFromDictionary:attributeDict];

// If there’s already an item for this key, it means we need to create an array
id existingValue = [parentDict objectForKey:elementName];
if (existingValue)
{
    NSMutableArray *array = nil;
    if ([existingValue isKindOfClass:[NSMutableArray class]])
    {
        // The array exists, so use it
        array = (NSMutableArray *) existingValue;
    }
    else
    {
        // Create an array if it doesn’t exist
        array = [NSMutableArray array];
        [array addObject:existingValue];

        // Replace the child dictionary with an array of children dictionaries
        [parentDict setObject:array forKey:elementName];
    }

    // Add the new child dictionary to the array
    [array addObject:childDict];
}
else
{
    // No existing value, so update the dictionary
    [parentDict setObject:childDict forKey:elementName];
}

// Update the stack
[dictionaryStack addObject:childDict];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// Update the parent dict with text info
NSMutableDictionary *dictInProgress = [dictionaryStack lastObject];

// Set the text property
if ([textInProgress length] > 0)
{
    // Get rid of leading + trailing whitespace
    [dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];

    // Reset the text
    [textInProgress release];
    textInProgress = [[NSMutableString alloc] init];
}

// Pop the current dict
[dictionaryStack removeLastObject];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// Build the text value
[textInProgress appendString:string];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
// Set the error pointer to the parser’s error object
*errorPointer = parseError;
}


@end

希望这可以帮助!!!

于 2013-03-06T06:02:36.233 回答
1

您可以使用XMLReader文件将 xml 数据解析为 NSDictionary 或 NSArray 或 MutableArray。将其用作:

NSError *error=nil;

NSString *responseString=[NSString stringWithFormat:@"<xml><Menu><pair><MenuCategory shortname=\"Starters Menu\" description_en=\"hgfhghgh\" image=\"Small.jpg\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"><MenuItems><menuItem price=\"666\" image=\"060649XSmall.jpg\" shortname=\"kandan\" description_en=\"kandan\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"/><menuItem price=\"250\" image=\"3.jpg\" shortname=\"Vegetable Soups\" description_en=\"Vegetable Soups\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"/><menuItem price=\"52\" image=\"3.jpg\" shortname=\"Mixed Starters\" description_en=\"Mixed Starters\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"/><menuItem price=\"45\" image=\"14.jpg\" shortname=\"Pumpkin soup\" description_en=\"Pumpkin soup\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"/><menuItem price=\"15\" image=\"15.jpg\" shortname=\"Almondrolledgoatsche\" description_en=\"Almondrolledgoatsche\" description_fr=\"\" description_ge=\"\" description_it=\"\" description_sp=\"\" description_ch=\"\"/></MenuItems></MenuCategory></pair></Menu></xml>"];

NSDictionary *dictionary=[XMLReader dictionaryForXMLString:responseString error:&error];

NSLog(@"dictioanry is %@",dictionary);

NSMutableArray *menuItemsArray=[[NSMutableArray alloc] initWithArray:[[[[[[dictionary valueForKey:@"xml"] valueForKey:@"Menu"] valueForKey:@"pair"] valueForKey:@"MenuCategory"] valueForKey:@"MenuItems"] valueForKey:@"menuItem"]];

NSLog(@"menu item array is %@",menuItemsArray);

控制台日志:--------

    dictioanry is {
    xml =     {
        Menu =         {
            pair =             {
                MenuCategory =                 {
                    MenuItems =                     {
                        menuItem =                         (
                                                        {
                                "description_ch" = "";
                                "description_en" = kandan;
                                "description_fr" = "";
                                "description_ge" = "";
                                "description_it" = "";
                                "description_sp" = "";
                                image = "060649XSmall.jpg";
                                price = 666;
                                shortname = kandan;
                            },
                                                        {
                                "description_ch" = "";
                                "description_en" = "Vegetable Soups";
                                "description_fr" = "";
                                "description_ge" = "";
                                "description_it" = "";
                                "description_sp" = "";
                                image = "3.jpg";
                                price = 250;
                                shortname = "Vegetable Soups";
                            },
                                                        {
                                "description_ch" = "";
                                "description_en" = "Mixed Starters";
                                "description_fr" = "";
                                "description_ge" = "";
                                "description_it" = "";
                                "description_sp" = "";
                                image = "3.jpg";
                                price = 52;
                                shortname = "Mixed Starters";
                            },
                                                        {
                                "description_ch" = "";
                                "description_en" = "Pumpkin soup";
                                "description_fr" = "";
                                "description_ge" = "";
                                "description_it" = "";
                                "description_sp" = "";
                                image = "14.jpg";
                                price = 45;
                                shortname = "Pumpkin soup";
                            },
                                                        {
                                "description_ch" = "";
                                "description_en" = Almondrolledgoatsche;
                                "description_fr" = "";
                                "description_ge" = "";
                                "description_it" = "";
                                "description_sp" = "";
                                image = "15.jpg";
                                price = 15;
                                shortname = Almondrolledgoatsche;
                            }
                        );
                    };
                    "description_ch" = "";
                    "description_en" = hgfhghgh;
                    "description_fr" = "";
                    "description_ge" = "";
                    "description_it" = "";
                    "description_sp" = "";
                    image = "Small.jpg";
                    shortname = "Starters Menu";
                };
            };
        };
    };
}

2013-03-06 11:52:31.500 MobileTrading[1212:11303] menu item array is (
        {
        "description_ch" = "";
        "description_en" = kandan;
        "description_fr" = "";
        "description_ge" = "";
        "description_it" = "";
        "description_sp" = "";
        image = "060649XSmall.jpg";
        price = 666;
        shortname = kandan;
    },
        {
        "description_ch" = "";
        "description_en" = "Vegetable Soups";
        "description_fr" = "";
        "description_ge" = "";
        "description_it" = "";
        "description_sp" = "";
        image = "3.jpg";
        price = 250;
        shortname = "Vegetable Soups";
    },
        {
        "description_ch" = "";
        "description_en" = "Mixed Starters";
        "description_fr" = "";
        "description_ge" = "";
        "description_it" = "";
        "description_sp" = "";
        image = "3.jpg";
        price = 52;
        shortname = "Mixed Starters";
    },
        {
        "description_ch" = "";
        "description_en" = "Pumpkin soup";
        "description_fr" = "";
        "description_ge" = "";
        "description_it" = "";
        "description_sp" = "";
        image = "14.jpg";
        price = 45;
        shortname = "Pumpkin soup";
    },
        {
        "description_ch" = "";
        "description_en" = Almondrolledgoatsche;
        "description_fr" = "";
        "description_ge" = "";
        "description_it" = "";
        "description_sp" = "";
        image = "15.jpg";
        price = 15;
        shortname = Almondrolledgoatsche;
    }
)
于 2013-03-06T06:07:08.813 回答
1

@Praveen 读取属性而不是元素

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
于 2013-03-06T06:35:34.513 回答
0

使用 NSMutableRequest 从 URL 获取数据

    NSString *stringURL=[NSString stringWithFormat:@"http://yourURL"];
NSURL *url=[NSURL URLWithString:stringURL];

NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
NSError *error;

NSURLResponse *response;

NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *responseString=[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];

NSDictionary *dictionary=[XMLReader dictionaryForXMLString:responseString error:&error];
于 2013-03-06T06:26:49.887 回答
0

如果您想使用 NSXMLParser,请使用它。

- (void)viewDidLoad

   {
      NSURL *url = [[NSURL alloc]initWithString:@"yourURL"];
        NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
        [parser setDelegate:self];
       BOOL result = [parser parse];
   }

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
    {
        NSLog(@"Did start element");
       if ( [elementName isEqualToString:@"root"])
        {
          NSLog(@"found rootElement");
          return;
        }
    }

    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
        NSLog(@"Did end element");
        if ([elementName isEqualToString:@"root"]) 
            {
              NSLog(@"rootelement end");
            }

    }
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {

       if([currentElementName isEqualToString:@"column"])
      {
           NSLog(@"Value %@",string);
      }

    }
于 2013-03-06T06:28:57.357 回答