1

I am creating an NSXMLDocument, from which I get a file defined in a constant USER_PRINTXML_URL, as follows:

NSXMLDocument *ads_user_printxml = [[NSXMLDocument alloc] initWithContentsOfURL: [NSURL URLWithString:USER_PRINTXML_URL]    options:(NSXMLNodePreserveWhitespace|NSXMLNodePreserveCDATA)                                          error:&ads_err];

Then I use XPath to get to the desired location in the XML file, as follows:

NSArray* ipp_folder = [[ads_user_printxml nodesForXPath:@".//root/printing/IPP"error:&ads_err] objectAtIndex:0];

Now, if I want to add NSXMLElements after the element in the XML file, how do I do it?

I have tried to do the following:

NSXMLElement *s= [ipp_folder objectAtIndex:0];

But this is generating a run time error. I also tried using an NSXMLNode instead of putting the data in an NSArray but again to no avail. I believe the solution is quite simple, but I can't for the life of me find an answer in the docs.

Thanks for any help.

Kevin
  • 1,469
  • 2
  • 19
  • 28

1 Answers1

2

-nodesForXPath:error: returns an NSArray*, but your second code snippet has already applied -objectAtIndex: to that. So, ipp_folder doesn't hold an array, it holds a pointer to an NSXMLNode. Fix its declared type.

Then, you can identify its parent using the -parent method and its index within the parent's children using the -index method. Then, assuming the parent is an NSXMLElement, you can do:

[[ipp_folder parent] insertChild:someNewNode atIndex:[ipp_folder index] + 1];
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • When you say "assuming the parent is an NSXMLElement", how can I declare it to be? So if the parent is in the XML file, and I want to insert a child between and how would I do it, given that [ipp_folder parent] returns an NSXMLNode, and not an NSXMLElement?? Thank you Ken! – Kevin Apr 25 '12 at 12:00
  • 1
    Wait, from the XPath you gave, the item itself will be the IPP element. If you want to insert into that, then you don't need its parent. (You originally said you wanted to insert after the IPP element.) So, you can just declare the variable as that type: `NSXMLElement* ipp_folder = ...`. If you want to verify that it is, you can check that `[ipp_folder kind] == NSXMLElementKind`. And then you'd just insert directly into that, rather than its parent, using `-addChild:`. – Ken Thomases Apr 25 '12 at 12:15
  • I meant to say into IPP, not after, sorry about that. You're right NSElement * ipp_folder =... does work.. I was confusing the return type I guess, declaring an NSArray when I was using the objectAtIndex:int parameter. Thanks a lot for your help Ken. – Kevin Apr 25 '12 at 12:22