0

我必须解析一个 3 级xml,如下所示:-

<Navigation>
    <parent>
       <parentheader>
           <![CDATA[ Home ]]>
       </parentheader>
       <url>my-profile</url>
       <Content>...</Content>
    </parent>
    <parent>
       <parentheader>
           <![CDATA[ Exhibiton ]]>
       </parentheader>
           <child>
                <childheader>
                <![CDATA[ London Exhibition ]]>
                </childheader>
                    <subchild>London Sub
                         <url>ezone</url>
                         <Content>...</Content>
                    </subchild>
           </child>
           <child>
                <childheader>
                 <![CDATA[ Asia Exhibition ]]>
                </childheader>
                <url>exhibition-asia-tour</url>
               <Content>...</Content>
           </child>
      </parent>
</Navigation>

我正在实现下面的NSXMLParser类和delegates方法是代码: -

.h 文件

@interface NavigationXMLParser : NSObject<NSXMLParserDelegate>
{
    NSXMLParser *xmlParser;
    NSMutableDictionary *item,*childDict,*subChildDict;
    NSMutableArray  *nodesArr,*childArr,*subChildArr;
    NSMutableString *parent, *url,*child,*subchild;
    NSString *currentElement;
    BOOL childBool;
}

-(void) fetchXMLData;

@end

.m 实现文件代码:-

@implementation NavigationXMLParser

-(void) fetchXMLData
{

    xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://exhibitors.gastechkorea.com/admin/XMl_APP_Navigation.aspx"]];

    [xmlParser setDelegate:self];
    [xmlParser setShouldResolveExternalEntities:NO];
    [xmlParser setShouldProcessNamespaces:NO];
    [xmlParser setShouldReportNamespacePrefixes:NO];
    [xmlParser parse];
}

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    nodesArr =[[NSMutableArray alloc] init];

    //[sharedSQLiteObj createFavoriteAgendaTableNamed:@"" withField1:@"" withField2:@"" withField3:@"" withField4:@""];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    {
        currentElement = [elementName copy];

        if ([elementName isEqualToString:@"parent"])
        {
            item = [[NSMutableDictionary alloc] init];
            parent = [[NSMutableString alloc]init];
            url = [[NSMutableString alloc]init];
        }
        else if ([elementName isEqualToString:@"child"])
        {
            child = [[NSMutableString alloc]init];
            childArr = [[NSMutableArray alloc] init];
            childDict = [[NSMutableDictionary alloc] init];
            url = [[NSMutableString alloc]init];

        }
        else if ([elementName isEqualToString:@"subchild"])
        {
            subchild = [[NSMutableString alloc]init];
            subChildArr = [[NSMutableArray alloc] init];
            subChildDict = [[NSMutableDictionary alloc] init];
            url = [[NSMutableString alloc]init];
        }
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if ([currentElement isEqualToString:@"parentheader"])
    {
        [parent appendString:string];
    }

    else if ([currentElement isEqualToString:@"url"])
    {
        [url appendString:string];
        if (!(child.length ==0))
        {
            if (subchild.length==0)
            {
                [childDict setObject:string forKey:@"url"];
            }
            else{
                [subChildDict setObject:string forKey:@"url"];
            }
        }
    }

   else if ([currentElement isEqualToString:@"childheader"])
    {
        [child appendString:string];

        if (!(string.length ==0))
        {
            [childDict setObject:string forKey:@"childheader"];
        }
    }
    else if ([currentElement isEqualToString:@"subchild"])
    {
        [subchild appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
        if (!([string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length ==0))
        {
            [subChildDict setObject:string forKey:@"subchild"];
            [subChildArr addObject:[subChildDict copy]];
            [childDict setObject:subChildArr forKey:@"subchild"];

            subChildDict = nil;
        };
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"child"])
    {
        if (!(childDict.count ==0)) {
            [childArr addObject:[childDict copy]];
            childDict = nil;
        }
    }
    if ([elementName isEqualToString:@"parent"])
    {
        [item setObject:[parent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"parent"];
        [item setObject:[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"url"];
        if (!(childArr.count ==0))
        {
            [item setObject:childArr forKey:@"child"];
        }
        else
        {
            [item setObject:@"" forKey:@"child"];
        }
        //[item setObject:[subchild stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:@"subchild"];
        [nodesArr addObject:[item copy]];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"nodesArr---%@",nodesArr);
}

@end

我从 xmlparser 类中得到了响应数组:-

(
        {
        child = "";
        parent = Home;
        url = "my-profile";
    },
        {
        child =         (
                        {
                childheader = "\n";
            }
        );
        parent = Exhibiton;
        url = "exhibition-asia-tour";
    },
        {
        child =         (
                        {
                childheader = "\n";
            }
        );
        parent = Calender;
        url = "http://www.google.com";
    }
)

我没有以正确的结构获取数据我在某些地方错了,但没有找到解决方案。我想在以下结构中获取数据:-

(
{ parent="…."
 child=""
url="……"
content="…."
}
{parent ="……"
child = ({ child="……";
          subchild= ({
                 name= "….."
                 url="….."
                 content="….."
            }
            {
                …………………….
                …..……………..
            })
           }
          {
        child="……"          
        ………………
           })
)
}

提前感谢您的帮助!!!

4

1 回答 1

0

一切都是关于如何使用这些NSXMLParserDelegate方法。您的XML文件可以为您提供以下信息:

[CDATA] 之间的字符,以及元素之间的字符。

因此,您需要实现以下Delegate方法来从XML文件中检索信息:

此方法将为您提供以下之间的每个字符串[CDATA]

-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSMutableString *str=[[NSMutableString alloc]initWithData:CDATABlock encoding:NSUTF8StringEncoding];
    [SomeArray addObject:str];
}

此方法将为您提供元素之间的每个字符串:

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    // here you need to alloc your string
    NSMutableString *parent = [[NSMutableString alloc]init];
    [parent appendString:string];
    [parent release];
}

NSMutableArray在和中检索数据后NSMutableString,您可以根据需要过滤数据。但这就是Parse你的XML文件的方式。

只是没那么复杂。祝你好运^_^

于 2013-05-29T10:48:42.500 回答