Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

Deconstructing an XML Document

The response XML Document will be received as an NSData object because the NSURLConnection from the previous step has no understanding of XML. Fortunately, NSXMLDocument has a way to translate that NSData back into an NSXMLDocument:

- (void)deconstructXMLResponse:(NSData *)data
  NSError *error;
  NSXMLDocument *responseXML = [[NSXMLDocument alloc] initWithData:data options:NSXMLDocumentTidyXML error:&error];
  if (!responseXML) {
    NSLog(@"Error reading response: %@", error);
  NSLog(@"Response received: \n%@", responseXML);

NSXMLDocument provides an init method that will accept an NSData object and translate the data for us. There are several options when constructing an NSXMLDocument from an NSData document, described in the following sections.


Formats HTML into valid XHTML during the processing of the document. When tidying, NSXMLDocument adds a line break before the close tag of a block-level element (<p>, <div>, <h1>, and so on); it also makes the string value of <br> or <hr> a line break. These operations make the string value of the HTML <body> more readable. After using this option, avoid outputting the document as anything other than the default kind: NSXMLDocumentXHTMLKind.


Changes malformed XML into valid XML during processing of the document. It also eliminates "pretty-printing" formatting, such as leading tab characters. However, it respects the xmlns:space="preserve" attribute.


Validates this document against its DTD (internal or external) or XML Schema.


Replaces all XInclude nodes in the document with the nodes referred to. XInclude allows clients to include parts of another XML document within a document.

After the NSXMLDocument object is constructed from the NSData, the elements and nodes can be extracted from it and processed as needed. In this example I simply printed out the XML document to the console.

  • + Share This
  • 🔖 Save To Your Account