0

If I have the following example code:

NSXMLDocument* doc = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL fileURLWithPath:@"file2.xml"] options:0 error:NULL];
NSXMLElement* root  = [doc rootElement];
NSArray* objectElements = [root nodesForXPath:@"//object" error:nil];

NSLog (@"doc - %@", doc);

NSXMLElement *c1 = [objectElements objectAtIndex:0];
NSLog (@"c1 --> %@",[c1 stringValue]);

//creating new element
NSXMLElement *c2 = [NSXMLElement elementWithName:@"value" stringValue:@"object new node"];
[c1 replaceChildAtIndex:0 withNode:c2]; 

NSLog (@"New doc - %@", doc);

I am trying to get an XML element and change its value to another (c2). The problem is that with the new node replacing, I am getting the element name as well inserted into the XML Document.

So, if I have

<element>old value</element>, 

I am now getting:

<element><newElement>new value</newElement></element>

How can I program the code so that

<newElement></newElement> 

do not get displayed? Thanks

P.S. Even simpler way of explaining:

Basically, I want to replace an Element with another element. So from

<e1>data1</e1>

I want to have

<e2>data 2</e2>

in its place.

Kevin
  • 1,469
  • 2
  • 19
  • 28

1 Answers1

0

I may be misunderstanding the question but it sounds like you are just trying to make the first element have the second ones attributes? Try something like:

- (void) method { 
    NSArry* attrs = [c2 attributes];
    [c1 setAttributes: attrs];
}

Hope that helps.

mdominick
  • 1,319
  • 1
  • 10
  • 21
  • I tried your suggestion but c1 remained as is. Basically, I want to replace an Element with another element. So from data1 I want to have data 2 in its place. – Kevin May 29 '12 at 05:56
  • OH, so you want the entire element replaced not just the data it contains? – mdominick May 29 '12 at 05:57
  • Hmm... so it looks like you are not actually writing your changes to the file on disk. So, the doc you are logging is in the same state as it was when you read it from disk. – mdominick May 29 '12 at 06:02
  • The saving to disk comes later.. However, I think that even without the saving part the updated document should be displayed.. The association of the element to the document is done automatically, no? – Kevin May 29 '12 at 06:04
  • I don't think it is automatic. I am rereading the NSXMLDocument documentation and there are a number of methods for removing / replacing child elements: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLDocument_Class/Reference/Reference.html – mdominick May 29 '12 at 06:10
  • you should be able to use [doc replaceChildAtIndex:index] to do what you want. – mdominick May 29 '12 at 06:11
  • I have already tried that as I have stated but the result is not what I want. Thanks. – Kevin May 29 '12 at 06:15