0

我有从 XML 文件创建的 GDataXMLDocument。

从文件中读取的 XML:

<Pages Count="1"> <Page PageNumber="1"></Page> </Pages>

我需要添加新的“页面”标签(以编程方式)。添加新“页面”后的 XML:

<Pages Count="2"> <Page PageNumber="1"></Page> <Page PageNumber="2"></Page> </Pages>

只要不需要将 stringValue 设置为“Page”标签,一切都可以;

XML 应如下所示:

<Pages Count="2"> <Page PageNumber="1">Some value</Page> <Page PageNumber="2">Some other value</Page> </Pages>

在程序中它看起来!(您可以使用 XMLString 方法看到这一点),但是当我将文档([文档 XMLData])保存回文件时,它看起来像这样:

<Pages Count="2"> <Page PageNumber="1">Some value</Page> <Page PageNumber="2"></Page> </Pages>

编号为 1 的页面(旧页面)具有价值,但编号为 2 的页面(新页面)没有。为什么我可以更改旧标签上的 stringValue,但不能更改新标签?

4

1 回答 1

0

它对我的工作,

GDataXMLElement *element = [GDataXMLElement elementWithName:@"Pages" stringValue:nil];
[element addAttribute:[GDataXMLNode attributeWithName:@"Count" stringValue:@"1"]];


GDataXMLElement *tempNode = [GDataXMLNode elementWithName:@"Page" stringValue:@"Some Value"];
[tempNode addAttribute:[GDataXMLNode attributeWithName:@"PageNumber" stringValue:@"1"]];

[element addChild:tempNode];

tempNode = [GDataXMLNode elementWithName:@"Page" stringValue:@"Some Other Value"];
[tempNode addAttribute:[GDataXMLNode attributeWithName:@"PageNumber" stringValue:@"2"]];

[element addChild:tempNode];

[element attributeForName:@"Count"].stringValue = @"2";

GDataXMLDocument *myDoc = [[GDataXMLDocument alloc] initWithRootElement:element];

NSData *data = [myDoc XMLData];

NSArray *dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [dirPath objectAtIndex:0];
path = [path stringByAppendingString:@"/myXml.xml"];

// log path file
NSLog(@"%@", path);

[data writeToFile:path atomically:YES];

data = nil;

data = [NSData dataWithContentsOfFile: path];

myDoc = nil;

myDoc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];

NSLog(@"%@", [myDoc rootElement]);
于 2014-03-21T13:34:37.473 回答