background image

IOS

 

     

开发之

 

 ----XML

 

     

常用操作

 

  

1.创建 XML 文件

1

//创建 XML 文件  

2

- (NSXMLDocument *)createXMLDocument:(NSString *)rootName{  

3

    NSLog(@"%@ with rootName %@", NSStringFromSelector(_cmd), rootName);  

4

    NSXMLElement *root = (NSXMLElement *)[NSXMLNode 

elementWithName:rootName];  

5

    [root addAttribute:[NSXMLNode attributeWithName:@"version" 

stringValue:@"1.0"]];  

6

    NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithRootElement:root]; 

7

    [xmlDoc setVersion:@"1.0"];  

8

    [xmlDoc setCharacterEncoding:@"UTF-8"];  

9

    [xmlDoc setRootElement:root];  

10

      

11

    return [xmlDoc autorelease];  

12

}  

2. 装载 XML 文件

13

- (NSXMLDocument *)loadXMLDocument:(NSString *)xmlFilePath{  

14

    assert(xmlFilePath);  

15

    NSXMLDocument *xmlDoc = nil;  

16

    NSError *error = nil;  

17

    @try {  

18

        NSURL *fileURL = [NSURL fileURLWithPath:xmlFilePath];  

19

        if (fileURL == nil) {  

20

            return nil;  

21

        }  

22

        xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:fileURL 

options:NSXMLDocumentTidyXML error:&error];  

23

    }  

24

    @catch (NSException * e) {  

25

          

26

    }  

27

    @finally {  

28

        return [xmlDoc autorelease];  

29

    }  

30

}  

3. 保存 XML 文件

31

- (BOOL) saveXMLFile:(NSString *)destPath :(NSXMLDocument *)xmlDoucment{  

32

    if (xmlDoucment == nil) {  

33

        return NO;