Search code examples
iosobjective-cxmlgdatagdataxml

Move XML element to different position with GDataXML


I'm current using Google's GDataXML library to manipulate XML in my iOS app. The xml is used to populate a table view, so one thing I'd like to support (but current don't) is the ability to move a row in the table view to a different spot using tableView:moveRowAtIndexPath:toIndexPath:.

Is there a way to do this easily using GDataXML?

For example, let's say this is what my xml looks like:

<root>
    <section>    
        <item>
              <name>Item 1</name>
              <description>The first item</description>
        </item>
        <item>
              <name>Item 2</name>
              <description>The second item</description>
        </item>
        <item>
              <name>Item 3</name>
              <description>The third item</description>
        </item>
    </section>
</root>

What would I have to do to move Item 3 to above where Item 1 is? Would it be similar to inserting a new element to the front of an array?

Thanks for the help!

Edit: Changed my example xml a bit. Could I just replace the whole <section> with a new one somehow?

UPDATE:

For anyone else wanting a method such as insertChild:atIndex:, check out the KissXML library. The transition from GDataXML to KissXML is very easy as most of the method names are the same. The KissXML library builds off of Apple's XML classes and it has a insertChild:atIndex: method.


Solution

  • You can form an mutable array with the items. Move around the items a bit and then you can save the items array as xml back.

    You can write the xml this way. I have created an array of dictionaries with key name and description

    GDataXMLElement *rootElement = [GDataXMLNode elementWithName:@"root"];
    GDataXMLElement *sectionElement = [GDataXMLNode elementWithName:@"section"];
    
    for (NSDictionary *dict in self.items) {
    
        GDataXMLElement *itemElement = [GDataXMLElement elementWithName:@"item"];
    
        GDataXMLElement *nameElement = [GDataXMLNode elementWithName:@"name" stringValue:dict[@"name"]];
        GDataXMLElement *descElement = [GDataXMLNode elementWithName:@"description" stringValue:dict[@"description"]];
    
        [itemElement addChild:nameElement];
        [itemElement addChild:descElement];
    
        [sectionElement addChild:itemElement];
    
    }
    
    [rootElement addChild:sectionElement];
    
    
    
    GDataXMLDocument *document = [[GDataXMLDocument alloc]
                                  initWithRootElement:rootElement];
    
    NSData *xmlData = document.XMLData;
    

    Now this xmlData can be written to fileLocation.

    You can take a look to this source code for complete implementation.