我有一个非常简单的xml文件,名称为options.xml

<Dat>
    <Name>Tom</Name>
    <Option>1</Option>
</Dat>

使用NSXML,我试图将“Tom”更改为“Jim”并保存文件。我怎样才能做到这一点。我阅读了许多文档,没有直接的解决方案。有人可以帮我提供代码吗?

更新:我最终尝试使用Gdatasxml
 -(void)saveToXML
{
NSString* path = [[NSBundle mainBundle] pathForResource:@"options" ofType:@"xml"];

NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];

GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"Dat"];

NSArray *mySettings = [doc.rootElement elementsForName:@"Dat"];

for (GDataXMLElement *mySet in mySettings)
{
    NSString *name;
    NSArray *names = [mySet elementsForName:@"Name"];
    if (names.count > 0)
    {
        GDataXMLElement *childElement = (GDataXMLElement *) [names objectAtIndex:0];
        name = childElement.stringValue;
        NSLog(childElement.stringValue);
        [childElement setStringValue:@"Jim"];
    }
}

[xmlData writeToFile:path atomically:YES];


}

但这并不保存数据。帮帮我。

最佳答案

在iOS中,编辑XML有点困难。您需要将原始xml解析为模型,然后形成xml。

您可以利用第三方数据库(例如GDataXML)从数据源中形成XML。

//Edited user info saved in a dictionary
NSDictionary *dictionary = @{@"Name": @"Jim", @"Option":@"1"};

GDataXMLElement *rootElement = [GDataXMLElement elementWithName:@"Dat"];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    GDataXMLElement *element = [GDataXMLElement elementWithName:key stringValue:obj];
    [rootElement addChild:element];
}];
//xml document is formed
GDataXMLDocument *document = [[GDataXMLDocument alloc]
                              initWithRootElement:rootElement];
NSData *xmlData = document.XMLData;

NSString *filePath = [self savedXMLPath];
//XML Data is written back to a filePath
[xmlData writeToFile:filePath atomically:YES];

关于iphone - XCODE NSXML更改元素值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17203494/

10-10 03:25