如何在iOS中的xml文件中保存和更新值?

时间:2011-07-08 06:32:21

标签: ios

在iOS中,我正在阅读xml文件。在这里,我想编写xml文件,我想更改XML文件的值,我想保存文件。

我的代码如下所示...请指导我如何在xml文件中保存和更新值。

-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName nodename:(NSString *)nodename{


    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    // the path to write file
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xml",fileName]];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
    if(fileExists) {
        NSError *error = nil;
        NSString *docStr;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        // the path to write file
        NSString *appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.xml",fileName]];

        BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
        if(fileExists)
        {
            NSLog(@"file exist in document");
            NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
            if (myData1) {  
                docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];

            } 
        }
        NSMutableString *str = [[NSMutableString alloc] init];
        NSString *aaa=[NSString stringWithFormat:@" <%@>%@</%@>",nodename,data,nodename];
        [str appendString:docStr];

        [str insertString:aaa atIndex:70];
        BOOL success = [str writeToFile:appFile  atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (!success) {
            NSLog(@"Error: %@", [error userInfo]);
        }
        else {
            NSLog(@"File write is successful");
        }
    }
}

6 个答案:

答案 0 :(得分:1)

简而言之,

  1. 使用XML解析器读取XML
  2. 表示某种对象结构中的XML(数据绑定)
  3. 修改对象结构;这是您插入新元素等的地方
  4. 使用XML序列化程序从对象结构
  5. 编写XML(不建议使用自己的XML)

    在步骤1和步骤4中,您可以通过NSData或直接从文件中读取,具体取决于XML解析器和编写器API。

    您可以使用NSXMLParser解析XML,将libxml(2)用于编写,或者使用其他读者和writersthis one由我来解析。)

答案 1 :(得分:1)

使用xcode链接库部分中提供的libxml2 dylib,并使用xmlwriter类创建xml文件。 示例代码

xmlTextWriterPtr _writer;
xmlBufferPtr _buf;
xmlChar *xmlString;
const char *_UTF8Encoding = "UTF-8";

_buf = xmlBufferCreate();
_writer = xmlNewTextWriterMemory(_buf, 0);

// <?xml version="1.0" encoding="UTF-8"?>
xmlTextWriterStartDocument(_writer, "1.0", _UTF8Encoding, NULL);

xmlTextWriterStartElement(_writer, BAD_CAST "root");

    // <request type="handle" action="update">
xmlTextWriterStartElement(_writer, BAD_CAST "child");

xmlString = [self xmlCharPtrForInput:[[NSString stringWithFormat:@"%@",objPatient.strFname] cStringUsingEncoding:NSUTF8StringEncoding] withEncoding:_UTF8Encoding];
xmlTextWriterWriteAttribute(_writer, BAD_CAST "fname", BAD_CAST xmlString);

xmlTextWriterEndElement(_writer);//Close child
xmlTextWriterEndElement(_writer); //close root here

方法xmlcharptrforinput是,

- (xmlChar *) xmlCharPtrForInput:(const char *)_input withEncoding:(const char *)_encoding 
{
    xmlChar *_output;
    int _ret;
    int _size;
    int _outputSize;
    int _temp;
    xmlCharEncodingHandlerPtr _handler;

    if (_input == 0)
        return 0;

    _handler = xmlFindCharEncodingHandler(_encoding);

    if (!_handler) {
        //NSLog(@"convertInput: no encoding handler found for '%s'\n", (_encoding ? _encoding : ""));
        return 0;
    }

    _size = (int) strlen(_input) + 1;
    _outputSize = _size * 2 - 1;
    _output = (unsigned char *) xmlMalloc((size_t) _outputSize);

    if (_output != 0) {
        _temp = _size - 1;
        _ret = _handler->input(_output, &_outputSize, (const xmlChar *) _input, &_temp);
        if ((_ret < 0) || (_temp - _size + 1)) {
            if (_ret < 0) {
                //NSLog(@"convertInput: conversion wasn't successful.\n");
            } else {
                //NSLog(@"convertInput: conversion wasn't successful. Converted: %i octets.\n", _temp);
            }   
            xmlFree(_output);
            _output = 0;
        } else {
            _output = (unsigned char *) xmlRealloc(_output, _outputSize + 1);
            _output[_outputSize] = 0;  //null terminating out
        }
    } else {
        //NSLog(@"convertInput: no memory\n");
    }

    return _output;
}

答案 2 :(得分:0)

对于Mac OS X和iOS平台,您可以使用NSUserDefaults类来保存和读取.plist,这是XML格式的属性列表。您的Xcode项目本身使用此类属性列表,例如Info.plist。 使用NSDefaults的另一个好处是它支持Objective-C对象的序列化,所以本质上你是在保存和读取二进制数据。

希望这会有所帮助,祝你好运。

如果这个答案对您有帮助,请将您的问题标记为已回答,谢谢。

答案 3 :(得分:0)

我建议您看下面给出的链接: http://reecon.wordpress.com/2010/04/09/reading-from-xml-file-in-objective-c/ 并且还看到 http://www.codeproject.com/KB/iPhone/iPhoneXMLParser.aspx 如果你没有得到足够的解决方案然后发表评论我会给出另一个解决方案。

答案 4 :(得分:0)

由于iPhone实际上没有DOM解析器(无NSXmlDocument),我建议使用第三方解析器。我最喜欢的是谷歌的GDataXMLNode。 GDataXMLNode

答案 5 :(得分:0)

使用GDataXMLNode Objective-C library

XML parsing and writing tutorial

您可以像这样更新,例如在Swift 3.0中&gt; :

do {
     let contactXMLDocument : GDataXMLDocument = try GDataXMLDocument(xmlString: strXMLData)
     let entryElement:GDataXMLElement = contactXMLDocument.rootElement()
     //remove first
     if let arrNameElements:Array<GDataXMLElement> = entryElement.elements(forName: "gd:name") as? Array<GDataXMLElement>{
         for nameElement:GDataXMLElement in arrNameElements {
            entryElement.removeChild(nameElement)
         }
      }
      //now add
      let nameElement : GDataXMLElement = GDataXMLNode.element(withName: "gd:name")
      //Other child to names
      //add name to entry
      entryElement.addChild(nameElement)

     //Generate Data
     let contactXMLData:Data = contactXMLDocument.xmlData()
     if let strUpdatedContactXML : String = String(data: contactXMLData, encoding: .utf8) 
     {
        print("Updated ContactXML : \(strUpdatedContactXML)")
        //save file here if needed
     }
}
catch {

}