Pritesh Lad
Pritesh Lad

Reputation: 53

How to change a value of xml tag using GDataXML in xcode 4.3?

I am new to using GDataXML to parse an xml file. I want to change the value of some intermediate xml tag in the file & write it back to the file.

Eg. I have following file..

<sheetData>
 <row r="7" spans="5:6" x14ac:dyDescent="0.25">
  <c r="E7" t="s">
   <v>0</v> 
  </c>
  <c r="F7" t="s">
    <v>1</v> 
  </c>
 </row>
 <row r="8" spans="5:6" x14ac:dyDescent="0.25">
  <c r="E8" t="s">
   <v>2</v> 
  </c>
  <c r="F8">
   <v>9890234654</v> 
  </c>
 </row>
</sheetData>

I want to update the value of phone no ('9890234654') to, say, 9503452366. How can I do that using GDataXML in iOS ?(I am using xcode 4.3.2)

I coudn't find any method to replace a tag value directly in the original xml tree.

Any help is appreciated. Thank you.

Upvotes: 3

Views: 823

Answers (1)

yoninja
yoninja

Reputation: 1962

Did you create the XML file/data? I suggest that you put namespace for the nodes so that they are easier to track. For example:

<sheetData xmlns="http://mypage.net/sheetdata">
  <row r="7" spans="5:6" x14ac:dyDescent="0.25" xmlns="http://mypage.net/r7">
    <c r="E7" t="s">
      <v>0</v> 
    </c>
    <c r="F7" t="s">
      <v>1</v> 
    </c>
  </row>
  <row r="8" spans="5:6" x14ac:dyDescent="0.25" xmlns="http://mypage.net/r8">
    <c r="E8" t="s">
      <v>2</v> 
    </c>
    <c r="F8">
      <v>9890234654</v> 
    </c>
  </row>
</sheetData>

Having the namespaces in place, here's a sample code to update the value:

//The sample xml data is assigned to this NSData object: myXMLData
//Create a GDataXMLDocument
NSError *error = nil;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:myXMLData options:0 error:&error];

//build a namespace dictionary
NSDictionary *ns = [NSDictionary dictionaryWithObjectsAndKeys:@"http://mypage.net/sheetdata", @"sd", @"http://mypage.net/r7", @"r7", "http://mypage.net/r8", @"r8", nil];

//Now here are some codes to change the value
NSError *err = nil;
GDataXMLNode *row8 = [[doc nodesForXPath:@"//r8:row" namespace:ns error:&err] objectAtIndex:0];
//Need to change value of second node
GDataXMLNode *f8 = [[row8 children] objectAtIndex:1];
GDataXMLNode *f8v = [[f8 children] objectAtIndex:0];
f8v.stringValue = @"9503452366";

//doc now has the xml with updated value. Just get the XML data, doc.XMLData, from it then convert it as you please

Upvotes: 1

Related Questions