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

时间:2022-11-19 13:31:56

I am a new iphone develaper.i am reading a xml file. Here I want to write the xml file and I want to change the values of the XML file and I want to save the file..

我是一个新的iphone develaper.i我正在读取一个xml文件。在这里,我想写xml文件,我想更改XML文件的值,我想保存文件..

My code is like below...... Please guide me how to save and update value in xml file...

我的代码如下......请指导我如何在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 个解决方案

#1


1  

In short,

  1. use an XML parser to read the XML
  2. 使用XML解析器来读取XML

  3. represent the XML in some kind of object structure (data binding)
  4. 在某种对象结构中表示XML(数据绑定)

  5. modify the object structure; this is where you insert your new elements etc
  6. 修改对象结构;这是您插入新元素等的地方

  7. use an XML serializer to write the XML (making your own XML is not recommended) from the object structure
  8. 使用XML序列化程序从对象结构中编写XML(不建议使用自己的XML)

In steps 1 and 4 you either go via NSData or read directly from file, depending on the XML parser and writer API.

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

You can use NSXMLParser to parse the XML, and libxml(2) to writer, alternatively other readers and writers (this one by me).

您可以使用NSXMLParser来解析XML,将libxml(2)用于解析,也可以使用其他读者和编写者(这是我的)。

#2


1  

Use libxml2 dylib available in the xcode links library sections and use xmlwriter class for creating your xml files. sample code

使用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

The method xmlcharptrforinput is,

方法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;
}

#3


0  

For the both the Mac OS X and iOS platforms, you can use the NSUserDefaults class for saving to and reading from .plist which is XML formatted property list. Your Xcode project itself uses such property list for example Info.plist. One additional benefits of using NSDefaults is it supports serialization of Objective-C objects so in essence you're saving and reading binary data.

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

Hope this helps, and good luck.

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

If this answer helps you, please mark your question as answered, thanks.

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

#4


0  

i suggest that u see link which is given to below: http://reecon.wordpress.com/2010/04/09/reading-from-xml-file-in-objective-c/ and see also http://www.codeproject.com/KB/iPhone/iPhoneXMLParser.aspx if u not getting sufficient solution then give comment i will give another solution.

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

#5


0  

Since the iPhone doesn't really have a DOM parser (No NSXmlDocument) I suggest using a third party parser. My favorite is GDataXMLNode from Google. GDataXMLNode

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

#6


0  

Use GDataXMLNode Objective-C library

使用GDataXMLNode Objective-C库

For XML parsing and writing tutorial

用于XML解析和编写教程

You can update like this for example in Swift 3.0 > :

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 {

}

#1


1  

In short,

  1. use an XML parser to read the XML
  2. 使用XML解析器来读取XML

  3. represent the XML in some kind of object structure (data binding)
  4. 在某种对象结构中表示XML(数据绑定)

  5. modify the object structure; this is where you insert your new elements etc
  6. 修改对象结构;这是您插入新元素等的地方

  7. use an XML serializer to write the XML (making your own XML is not recommended) from the object structure
  8. 使用XML序列化程序从对象结构中编写XML(不建议使用自己的XML)

In steps 1 and 4 you either go via NSData or read directly from file, depending on the XML parser and writer API.

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

You can use NSXMLParser to parse the XML, and libxml(2) to writer, alternatively other readers and writers (this one by me).

您可以使用NSXMLParser来解析XML,将libxml(2)用于解析,也可以使用其他读者和编写者(这是我的)。

#2


1  

Use libxml2 dylib available in the xcode links library sections and use xmlwriter class for creating your xml files. sample code

使用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

The method xmlcharptrforinput is,

方法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;
}

#3


0  

For the both the Mac OS X and iOS platforms, you can use the NSUserDefaults class for saving to and reading from .plist which is XML formatted property list. Your Xcode project itself uses such property list for example Info.plist. One additional benefits of using NSDefaults is it supports serialization of Objective-C objects so in essence you're saving and reading binary data.

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

Hope this helps, and good luck.

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

If this answer helps you, please mark your question as answered, thanks.

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

#4


0  

i suggest that u see link which is given to below: http://reecon.wordpress.com/2010/04/09/reading-from-xml-file-in-objective-c/ and see also http://www.codeproject.com/KB/iPhone/iPhoneXMLParser.aspx if u not getting sufficient solution then give comment i will give another solution.

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

#5


0  

Since the iPhone doesn't really have a DOM parser (No NSXmlDocument) I suggest using a third party parser. My favorite is GDataXMLNode from Google. GDataXMLNode

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

#6


0  

Use GDataXMLNode Objective-C library

使用GDataXMLNode Objective-C库

For XML parsing and writing tutorial

用于XML解析和编写教程

You can update like this for example in Swift 3.0 > :

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 {

}