XML解析(android及ios的2种方法)

前端之家收集整理的这篇文章主要介绍了XML解析(android及ios的2种方法)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


最近要做一个ios的项目,正努力熟悉ios的语法及工具。近期可能文章更多关于某一知识点android和ios的实现和对比。

也能更好的掌握这门语言,及更深了解android。

本文大纲:

1.android的sax解析。

2.ios的sax解析。

3.android的pull解析。

4.ios的tbxml解析。

本文没有什么好讲的只是分享demo。

首先用到的xml文件

person.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id = "23">
		<name>NEwii</name>
		<age>21</age>
	</person>
	<person id = "20">
		<name>WiiWill</name>
		<age>25</age>
	</person>
</persons>


1.android sax

Person类

@H_404_30@public class Person { public String id; public String name; public String age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }


解析回调类

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class SAXForHandler extends DefaultHandler {

	private String tag;
	private List<Person> persons;
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.startDocument();
		persons=new ArrayList<Person>();
	}

	@Override
	public void endDocument() throws SAXException {
		// TODO Auto-generated method stub
		super.endDocument();
		Person person;
		for(int i=0;i<persons.size();i++)
        {
        	person=persons.get(i);
        	Log.v("id",person.getId());
        	Log.v("name",person.getName());
        	Log.v("age",person.getAge());
        }
	}

	@Override
	public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		super.startElement(uri,localName,qName,attributes);
		tag=localName;
		if(localName.equals("person"))
		{
			Person person=new Person();
			person.setId(attributes.getValue(0));
			persons.add(person);
		}
	}

	@Override
	public void endElement(String uri,String qName)
			throws SAXException {
		// TODO Auto-generated method stub
        
	}

	@Override
	public void characters(char[] ch,int start,int length)
			throws SAXException {
		// TODO Auto-generated method stub
		String data=new String(ch,start,length);
		
		if(!data.trim().equals(""))
		{
			Person person=persons.get(persons.size()-1);
			if(tag.equals("name"))
				person.setName(data);
			if(tag.equals("age"))
				person.setAge(data);
		}
		super.characters(ch,length);
	}

	public List<Person> getPersons() {
		return persons;
	}

	public void setPersons(List<Person> persons) {
		this.persons = persons;
	}
    
}


private void sax_xml() {
		// TODO Auto-generated method stub
		try {
			InputStream in = getClass().getResourceAsStream("person.xml");
			SAXForHandler handler = new SAXForHandler();
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			saxParser.parse(in,handler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

2.ios xml

Person

//
//  Person.h
//  DataParse
//
//  Created by lvshujun on 14-4-9.
//  Copyright (c) 2014年 yunda. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    @private
    NSString *name;
    NSString *id;
    NSString *age;
}
@property NSString *name;
@property NSString *id;
@property NSString *age;
@end


//
//  Person.m
//  DataParse
//
//  Created by lvshujun on 14-4-9.
//  Copyright (c) 2014年 yunda. All rights reserved.
//

#import "Person.h"

@implementation Person
@synthesize age;
@synthesize name;
@synthesize id;
@end


实现协议类

//
//  ViewController.h
//  DataParse
//
//  Created by tiancai on 14-4-9.
//  Copyright (c) 2014年 yunda. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSXMLParserDelegate>
{
    @private
    NSMutableArray *dictionary;
    NSString *tag;
    int i;
}
@property NSMutableArray *dictionary;
@property NSString *tag;
@property int i;
@end


//
//  ViewController.m
//  DataParse
//
//  Created by lvshujun on 14-4-9.
//  Copyright (c) 2014年 yunda. All rights reserved.
//

#import "ViewController.h"
#include "Person.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize dictionary;
@synthesize tag;
@synthesize i;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view,typically from a nib.
    NSString *xmlPath=[[NSBundle mainBundle] pathForResource:@"person" ofType:@"xml"];
    NSString *xmlString=[NSString stringWithContentsOfFile:xmlPath encoding:NSUTF8StringEncoding error:NULL];
    NSData *data=[NSData dataWithBytes:[xmlString UTF8String] length:xmlString.length];
    NSLog(xmlString);
    //NSXMLParser *parser=[[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:xmlPath]];
    //parser.delegate=self;
    NSXMLParser *parser=[[NSXMLParser alloc] initWithData:data];
    [parser setDelegate:self];
    [parser parse];
    NSLog(@"viewDidLoad");
    NSString *listPath=[[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"];
    NSString *listString=[NSString stringWithContentsOfFile:listPath encoding:NSUTF8StringEncoding error:NULL];
    NSDictionary *dictionary=[[NSDictionary alloc] initWithContentsOfFile:listPath];
    NSLog([[dictionary allKeys] objectAtIndex:0]);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    dictionary=[NSMutableArray arrayWithCapacity:2];
}
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    //NSLog(@"SIZE%d",di);
    Person *person=dictionary[1];
    NSLog(@"parserDidEndDocument");
    NSLog([person age]);
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)
    string
{
    
    if([tag isEqualToString:@"name"])
    {
 
        Person *person=[dictionary lastObject];
        [person setValue:string forKey:@"name" ];
        
    }
    else if([tag isEqualToString:@"age"])
    {
        Person *person=[dictionary lastObject];
        [person setValue:string forKey:@"age"];
    }
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    tag=nil;
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    tag=elementName;
    if([tag isEqualToString:@"person"])
    {
         Person *person=[Person new];
        [person setValue:[attributeDict objectForKey:@"id"] forKey:@"id"];
        [dictionary addObject:person];
    }
    
}
-(void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    
}
@end


3.pull解析 android

private void pull_xml() {
		// TODO Auto-generated method stub
		int event;
		List<Person> persons=null;
		try {
			XmlPullParser parser = Xml.newPullParser();
			InputStream is = getClass().getResourceAsStream("person.xml");
			parser.setInput(is,"utf-8");
			event=parser.getEventType();
			while(event!=XmlPullParser.END_DOCUMENT)
			{
				switch (event) {
				case XmlPullParser.START_DOCUMENT:
					persons=new ArrayList<Person>();
					break;

				case XmlPullParser.START_TAG:
					String tag=parser.getName();
					if(tag.equals("person"))
					{
						Person person=new Person();
						person.setId(parser.getAttributeValue(0));
						persons.add(person);
					}
					else if(!tag.equals(""))
					{
						
						if(tag.equals("name"))
						{
							Person person=persons.get(persons.size()-1);
							person.setName(parser.nextText());
						}
						else if(tag.equals("age"))
						{
							Person person=persons.get(persons.size()-1);
							person.setAge(parser.nextText());
						}
					}
					break;
				
				default:
					break;
				}
				event=parser.next();
			}
			Person person;
			for(int i=0;i<persons.size();i++)
	        {
	        	person=persons.get(i);
	        	Log.v("id",person.getId());
	        	Log.v("name",person.getName());
	        	Log.v("age",person.getAge());
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


4.tbxml解析

1.首先下载tbxml

2.把这2个文件夹放入你的工程

3.引入libz.dylib库 千万不要引入到测试工程中

4.加入宏定义#defin_ARC_ENABLED

5 加入同文件

//
//  ViewController.m
//  xml
//
//  Created by lenovo on 14-4-12.
//  Copyright (c) 2014年 lenovo. All rights reserved.
//

#import "ViewController.h"
#import "TBXML.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view,typically from a nib.
    [self start];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void) start
{
    NSLog(@"解析完成...");
    self.notes = [NSMutableArray new];
    
    TBXML* tbxml = [[TBXML alloc] initWithXMLFile:@"Notes.xml" error:nil];
    
    TBXMLElement * root = tbxml.rootXMLElement;
    
	// if root element is valid
	if (root) {
        
		TBXMLElement * noteElement = [TBXML childElementNamed:@"Note" parentElement:root];
        
        while ( noteElement != nil) {
            
            NSMutableDictionary *dict = [NSMutableDictionary new];
            
            TBXMLElement *CDateElement = [TBXML childElementNamed:@"CDate" parentElement:noteElement];
            if ( CDateElement != nil) {
                NSString *CDate = [TBXML textForElement:CDateElement];
                [dict setValue:CDate forKey:@"CDate"];
            }
            
            TBXMLElement *ContentElement = [TBXML childElementNamed:@"Content" parentElement:noteElement];
            if ( ContentElement != nil) {
                NSString *Content = [TBXML textForElement:ContentElement];
                [dict setValue:Content forKey:@"Content"];
            }
            
            TBXMLElement *UserIDElement = [TBXML childElementNamed:@"UserID" parentElement:noteElement];
            if ( UserIDElement != nil) {
                NSString *UserID = [TBXML textForElement:UserIDElement];
                [dict setValue:UserID forKey:@"UserID"];
            }
            
            //获得ID属性
            NSString *_id = [TBXML valueOfAttributeNamed:@"id" forElement:noteElement error:nil];
            [dict setValue:_id forKey:@"id"];
            
            [_notes addObject:dict];
            
            
            noteElement = [TBXML nextSiblingNamed:@"Note" searchFromElement:noteElement];
            
		}
    }
    
    NSLog(@"解析完成...");
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadViewNotification" object:self.notes userInfo:nil];
    self.notes = nil;
    
}

@end
原文链接:https://www.f2er.com/xml/298874.html

猜你在找的XML相关文章