Json&xml Analysis Summary

Source: Internet
Author: User

JSON & XML parsing

JSON (data transfer):

JSON has an object (dictionary) and an array of two data formats. Dictionary with "{}", array with "[]". Actually also Key-value (string, numeric, Boolean type, object, empty object, array) key-value pairs.

JSON can be converted to and from Object-c, which is the parsing process of JSON (forward and reverse parsing-to illustrate the positive inverse of its definition), which can be used to persist data, write JSON data to a file (reverse), and read data from a file (forward).

JSON->object-c (forward): Jsondata->jsonarray/jsondictionary

Object-c, JSON (reverse): Jsonarray/jsondictionary->jsonstring->jsondata

The system provides the Nsjsonserialization class for JSON parsing, which provides many parsing methods.

Convert Dictionary to JSON

Nsdictionary *[email protected]{

@ "name": @ "Jessi",

@ "Age": @19,

@ "Married": @ (True),

@ "friend": @[@ "Pwy", @ "WM", @ "Zjay"

],

};

The object of NSData is binary data transforming dictionary into binary data for transfer and conversion to string by string

NSData *jsondata;

if ([Nsjsonserialization isvalidjsonobject:dic])

{

Jsondata=[nsjsonserialization datawithjsonobject:dic options:nsjsonwritingprettyprinted Error:nil];

}

NSString *str=[[nsstring Alloc]initwithdata:jsondata encoding:nsutf8stringencoding];

Array conversion JSON

Nsarray *[email protected][@123,@ "Pwy", @ "Sting", @1];

NSData *data;

if ([Nsjsonserialization Isvalidjsonobject:array])

{

Data=[nsjsonserialization Datawithjsonobject:array options:nsjsonwritingprettyprinted Error:nil];

}

NSString *str1=[[nsstring Alloc]initwithdata:data encoding:nsutf8stringencoding];

JSON to dictionary and array variability

Correct JSON string format to succeed

Nsjsonreadingmutablecontainers to variable dictionaries and arrays

Nsjsonreadingmutableleaves/nsjsonreadingallowfragments to immutable dictionaries and arrays

[Email protected] "{\" name\ ": \" jessi\ ", \" age\ ": 12,\" height\ ": 165}";

NSLog (@ "str1%@", str1);

DATA=[STR1 datausingencoding:nsutf8stringencoding];

Nsdictionary *dic1=[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil];

XML (data transfer):

XML is only a dictionary of data format, is a tree-type storage structure, must have a root node, nesting (with the idea of the tree to think). XML does not store data as a key-value pair as JSON does, but it also means that XML stores data with tags and values. XML data write (save) files can persist data and facilitate network transmission.

There are a number of XML parsing tools, including: Libxml2->hpple, Gdataxml, Kissxml, nsxmlparser-> xmldictionary, which we often use today xmldictionary,hpple.

XML parsing Method 1:

SAX (simple API for XML) line-by-row parsing, fast memory consumption, no need to build the document tree in memory->nsxmlparser-> xmldictionary

Prepare before parsing:

Parsing of the XML (after the parser is loaded and then parsing the contents of the XML file) does not begin to parse.

Single-Case model

Xmldictionaryparser *parser=[xmldictionaryparser Sharedinstance];

Save node name, default only stub node name

Parser.nodenamemode=xmldictionarynodenamemodealways;

Keep annotations

Parser.preservecomments=yes;

To save a property value in a dictionary

Parser.attributesmode=xmldictionaryattributesmodedictionary;

Nsdictionary *xmdic=[nsdictionary dictionarywithxmlfile: @ "/users/apple/desktop/test1.xml"];

Nsdictionary *[email protected]{

@ "__name": @ "Student",

@ "__attributes": @{@ "id": @ "abc" @ "Class": @ "Conquer"},

@ "name": @ "Jessi",

@ "Age": @18,

@ "Gender": @ "female",

@ "Friends": @{

@ "friend": @[

@{@ "__text": @ "Nobody",}

]

}

};

NSString *xmlstring=[dic xmlstring];

[xmlstring WriteToFile: @ "/users/apple/desktop/test2.xml" Atomically:yes encoding:nsutf8stringencoding Error:nil];

NSString *xmlfilepath;

Xmlfilepath = [[NSBundle mainbundle] pathforresource:@ "test1" oftype:@ "xml"];

NSLog (@ "xmlfilepath->%@", Xmlfilepath);

Xmlparse parsing an XML file

Xmldocptr doc = Xmlparsefile ([Xmlfilepath utf8string]);

Xmlparse parsing xml file read from memory

NSString *xmlstr = [NSString stringwithcontentsoffile:xmlfilepath encoding:nsutf8stringencoding Error:nil];

Nssstring-CString

Xmldocptr Doc1 = Xmlparsememory ([Xmlstr utf8string], (int) [XMLSTR lengthofbytesusingencoding:nsutf8stringencoding]);

Get root node

Xmlnodeptr root = xmldocgetrootelement (doc);

if (xmlstrcmp (Root->name, (const XMLCHAR *) "student") = = 0)

{

NSLog (@ "Rootname is student");

Get child nodes

root = root->xmlchildrennode;//parent node points to child nodes

Child nodes are not empty, you can continue to find child nodes

while (root = NULL)

{

if (!xmlstrcmp (Root->name, (const XMLCHAR *) "Books"))

{

Books's sub-node book

Xmlnodeptr book = root->xmlchildrennode;

while (book! = NULL)

{

if (!xmlstrcmp (Book->name, (const XMLCHAR *) "book")

{

NSLog (@ "name:%s", book->name);

Get the property of type

NSLog (@ "type:%s", Xmlgetprop (book, (const XMLCHAR *) "type");

Xmlchar *content = xmlnodelistgetstring (Doc, Book->children, 1);

NSLog (@ "content:%@", [NSString stringwithcstring: (const char *) content encoding:nsutf8stringencoding]);

}

Gets the next node sibling node for siblings

Book = book->next;

}

}

root = root->next;

}

Xmlfree (DOC);

}

XML parsing Method 2:

DOM (Document Object model), when parsing the entire document into memory, using C library libxml.dylib Implementation of the resolution, you can modify and edit the document->libxml2-> Hpple (often used to parse network data)

Prepare before parsing:

An example of parsing the embarrassing encyclopedia:

NSData *dataout = [NSData datawithcontentsoffile:@ "/users/apple/desktop/qiubai1.html"];

Tfhpple *doc = [[Tfhpple alloc] initwithhtmldata:dataout encoding:@ "Utf-8"];

Take out a page of 20 stories

Nsarray *result = [Doc searchwithxpathquery:@ "//div[@class = ' article block untagged mb15 ']";

For (tfhppleelement *elem in result)

{

Climb out of the head

Nsarray *headimg = [Elem searchwithxpathquery:@ "//div[@class = ' author ']/a/img"];

Tfhppleelement *headerimg = [headimg firstobject];

NSString *headstr = [headerimg attributes][@ "src"];

NSLog (@ "headerstr->%@", headstr);

Crawl out user name

Tfhppleelement *nickname = [[Elem searchwithxpathquery:@]//div[@class = ' author ']/a "] firstobject];

NSString *nicknamestr1 = [nickname content];

Go blank-this method is useless

NSString *NICKNAMESTR2 = [nicknameStr1 stringbytrimmingcharactersinset:[nscharacterset whitespacecharacterset];

string splitting \ n \ nickname \ n

Nsarray *nick = [nicknameStr1 componentsseparatedbystring:@ "\ n"];

NSString *nicknamestr = nick[2];

NSLog (@ "nickname->%@", nicknamestr);

Tfhppleelement *story = [[Elem searchwithxpathquery:@//div[@class = ' content '] '] firstobject];

NSString *storycontent = [story content];

NSLog (@ "storycontent->%@", storycontent);

Tfhppleelement *fun = [[Elem searchwithxpathquery:@]//div[@class = ' stats ']/span "] firstobject];

NSString *funny = [fun content];

NSLog (@ "funny->%@", funny);

Tfhppleelement *conmment = [[Elem searchwithxpathquery:@]//div[@class = ' stats ']/span/a "] firstobject];

NSString *conmments1 = [conmment content];

Nsarray *con = [conmments1 componentsseparatedbystring:@ "\ n"];

NSString *conmments = con[1];

Json&xml Analysis Summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.