<note><to>George</to><from>John</from><heading>Reminder</heading><body>Don"t forget the meeting!</body></note>
上面的这条便签具有自我描述性。它拥有标题以及留言,同时包含了发送者和接受者的信息。但是,这个 XML 文档仍然没有做任何事情。它仅仅是包装在XML标签中的纯粹的信息。我们需要编写软件或者程序,才能传送、接收和显示出这个文档。
<p>This is a paragraph<p>This is another paragraph在XML中,省略关闭标签是非法的。所有元素都必须有关闭标签:
<p>This is a paragraph</p><p>This is another paragraph</p>注释:您也许已经注意到XML声明没有关闭标签。这不是错误。声明不属于XML本身的组成部分。它不是XML元素,也不需要关闭标签。
<Message>这是错误的。</message><message>这是正确的。</message>1.2.3 XML标签对大小写敏感
<b><i>This text is bold and italic</b></i>在 XML中,所有元素都必须彼此正确地嵌套:
<b><i>This text is bold and italic</i></b>在上例中,正确嵌套的意思是:由于<i>元素是在<b>元素内打开的,那么它必须在<b>元素内关闭。
<root> <child> <subchild>.....</subchild> </child></root>1.2.5 XML的属性值须加引号
<note date=08/08/2008><to>George</to><from>John</from></note> <note date="08/08/2008"><to>George</to><from>John</from></note>1.2.6 实体引用
<message>if salary < 1000 then</message>为了避免这个错误,请用实体引用来代替 “<” 字符:
<message>if salary < 1000 then</message>在 XML 中,有 5 个预定义的实体引用:
< < 小于> > 大于& & 和号" " 单引号" " 引号注释:在 XML 中,只有字符 “<” 和 “&” 确实是非法的。大于号是合法的,但是用实体引用来代替它是一个好习惯。
<!-- This is a comment -->在 XML 中,空格会被保留 HTML 会把多个连续的空格字符裁减(合并)为一个:
HTML: Hello my name is David.输出: Hello my name is David. 在 XML 中,文档中的空格不会被删节。
<message>此文本也会被解析</message>解析器之所以这么做是因为 XML 元素可包含其他元素,就像这个例子中,其中的元素包含着另外的两个元素(first和last):
<name><first>Bill</first><last>Gates</last></name>而解析器会把它分解为像这样的子元素:
<name> <first>Bill</first> <last>Gates</last></name>1.3.2 转义字符
<message>if salary < 1000 then</message>为了避免此类错误,需要把字符 “<” 替换为实体引用,就像这样:
<message>if salary < 1000 then</message>在 XML 中有 5 个预定义的实体引用:
< < 小于> > 大于& & 和号" " 省略号" " 引号注释:严格地讲,在XML中仅有字符”<“和”&“是非法的。省略号、引号和大于号是合法的,但是把它们替换为实体引用是个好的习惯。
<?xml version="1.0" encoding="utf-8"?><response><header><respcode>0</respcode><total>1736</total></header><result><album> <album_id>320305900</album_id> <title> <![CDATA[ 电影侃侃之初恋永不早 ]]> </title> <tag> <![CDATA[ 18岁以上 当代 暧昧 华语 ]]> </tag> <img>http://pic9.qiyipic.com/image/20141016/ec/e0/v_108639906_m_601_120_160.jpg</img> <img180236>http://pic9.qiyipic.com/image/20141016/ec/e0/v_108639906_m_601_180_236.jpg</img180236> <img11577>http://pic9.qiyipic.com/image/20141016/ec/e0/v_108639906_m_601_115_77.jpg</img11577> <img220124>http://pic9.qiyipic.com/image/20141016/ec/e0/v_108639906_m_601_284_160.jpg</img220124> <category_id>1</category_id> <score>0.0</score> <voters>0</voters> <tv_sets>0</tv_sets> <duration>00:38:57</duration> <year> <![CDATA[ 2014 ]]> </year> <tv_focus>跟爱情片学把妹心经</tv_focus> <episode_count>1</episode_count> <directors> <![CDATA[ 关雅荻 ]]> </directors> <mainactors> <![CDATA[ 关雅荻 ]]> </mainactors> <actors> <![CDATA[ ]]> </actors> <vv2> <![CDATA[ 15 ]]> </vv2> <timeText> <![CDATA[ 今天 ]]> </timeText> <first_issue_time> <![CDATA[ 2014-10-16 ]]> </first_issue_time> <up>0</up> <down>0</down> <download>1</download> <purchase_type>0</purchase_type> <hot_or_new>0</hot_or_new> <createtime>2014-10-16 12:25:08</createtime> <purchase>0</purchase> <desc> <![CDATA[本期节目主持人介绍新近上映的口碑爱情片,。主持人轻松幽默的罗列出胡鳄鱼导演拍摄的爱情片越来越接地气,博得观众的认同和追捧,更提出“初恋永远不嫌早”的口号。观众可以跟着爱情片学习把妹心经。]]> </desc> <ip_limit>1</ip_limit> <episodes/></album></result> </response>这是展示一部电影的具体数据,包括标题、介绍、内容、导演、演员、时长、上映年份等很多内容。
<?xml version="1.0" encoding="ISO-8859-1"?><note><to>George</to><from>John</from><heading>Reminder</heading><body>Don"t forget the meeting!</body></note>第一行是XML声明。它定义XML的版本(1.0)和所使用的编码(ISO-8859-1=Latin-1/西欧字符集)。
<note>接下来 4 行描述根的 4 个子元素(to, from, heading 以及 body):
<to>George</to><from>John</from><heading>Reminder</heading><body>Don"t forget the meeting!</body>最后一行定义根元素的结尾:
</note>从本例可以设想,该XML文档包含了John给George的一张便签。
<root> <child> <subchild>.....</subchild> </child></root>父、子以及同胞等术语用于描述元素之间的关系。父元素拥有子元素。相同层级上的子元素成为同胞(兄弟或姐妹)。
public ResultInfo onParser(Element rootElement) { int resp = -1; try {String elName = "header/respcode";resp = Integer.parseInt(selectNodeString(rootElement, elName)); } catch (NumberFormatException e) {e.printStackTrace(); } Log.d(TAG, "resp= " + resp); if (resp != 0) {return null; } ResultInfo searchResultInfo = new ResultInfo(); // Parse Search Weight @SuppressWarnings("rawtypes") final List weights = rootElement.selectNodes(rootElement.getPath() + "/" + "result/weights/weight"); ResultInfo[] resultFilterInfos = parseVideos(weights); if (resultFilterInfos != null) {ResultInfo weight = new ResultInfo();weight.putResultInfoArray(ResultInfo.KEY_VIDEOS, resultFilterInfos);searchResultInfo.putResultInfo(ResultInfo.KEY_WEIGHT, weight); } // Parse Albums @SuppressWarnings("rawtypes") final List albums = rootElement.selectNodes(rootElement.getPath() + "/" + "result/albums/album"); ResultInfo[] resultInfos = parseVideos(albums); if (resultInfos != null) {ResultInfo album = new ResultInfo();album.putResultInfoArray(ResultInfo.KEY_VIDEOS, resultInfos);searchResultInfo.putResultInfo(ResultInfo.KEY_SEARCH, album); } return searchResultInfo;}1.7.2 Step 2
private ResultInfo[] parseVideos(final List nodes) { if (nodes != null && nodes.size() > 0) {final int size = nodes.size();final ResultInfo[] vis = new ResultInfo[size];int i = 0;for (Object o : nodes) { if (o instanceof Element) {final Element videoElement = (Element) o;ResultInfo vi = parseVideo(videoElement);vis[i] = vi; } i++;}return vis; } return null;}1.7.3 Step 3
private ResultInfo parseVideo(final Element videoElement) { final String id = videoElement.elementText("album_id"); final String title = videoElement.elementText("title"); final String categoryId = videoElement.elementText("category_id"); final String categoryName = videoElement.elementText("category_name"); final String count = videoElement.elementText("count"); final String imgUrl = videoElement.elementText("img180236"); final String duration = videoElement.elementText("duration"); final String mainactors = videoElement.elementText("mainactors"); final String sitename = videoElement.elementText("site_name"); final String videourl = videoElement.elementText("vedio_url"); final String sort = videoElement.elementText("sort"); final String tv_id = videoElement.elementText("tv_id"); ResultInfo vi = new ResultInfo(); vi.putString(VideoInfo.ID, id); vi.putString(VideoInfo.TITLE, title); vi.putString(VideoInfo.CATEGORY_ID, categoryId); vi.putString(VideoInfo.CATEGORY_NAME, categoryName); vi.putString(VideoInfo.COUNT, count); vi.putString(VideoInfo.IMG_URL, imgUrl); vi.putString(VideoInfo.DURATION, duration); vi.putString(VideoInfo.MAINACTORS, mainactors); vi.putString(VideoInfo.SITENAME, sitename); vi.putString(VideoInfo.VIDEOURL, videourl); vi.putString(VideoInfo.SORT, sort); vi.putString(VideoInfo.TV_ID, tv_id); return vi;}1.7.4 Step 4
public static ArrayList<SearchVideoInfo> getSearchVideoInfo(ResultInfo searchResultInfo) { ResultInfo resultInfo = null; ResultInfo[] videos = null; ArrayList<SearchVideoInfo> searchVideoInfos = null; if (searchResultInfo != null) {resultInfo = searchResultInfo.getResultInfo(ResultInfo.KEY_SEARCH); } if (resultInfo != null) {videos = resultInfo.getResultInfoArray(ResultInfo.KEY_VIDEOS); } if (videos != null && videos.length > 0) {searchVideoInfos = new ArrayList<SearchVideoInfo>(videos.length);for (ResultInfo video : videos) { SearchVideoInfo searchInfo = new SearchVideoInfo(); searchInfo.setAlbum_id(video.getString(VideoInfo.ID)); searchInfo.setTitle(video.getString(VideoInfo.TITLE)); searchInfo.setChannel_id(video.getString(VideoInfo.CATEGORY_ID)); searchInfo.setImgUrl(video.getString(VideoInfo.IMG_URL)); searchInfo.setDuration(video.getString(VideoInfo.DURATION)); searchInfo.setMainActors(video.getString(VideoInfo.MAINACTORS)); searchInfo.setSiteName(video.getString(VideoInfo.SITENAME)); searchInfo.setVideo_url(video.getString(VideoInfo.VIDEOURL)); searchInfo.setOrder(video.getString(VideoInfo.SORT)); searchInfo.setTv_id(video.getString(VideoInfo.TV_ID)); // searchInfo.setContinueType(video.getString(VideoInfo.CONTINUETYPE)); searchVideoInfos.add(searchInfo);} } if (searchVideoInfos == null) {MyLog.e(TAG, "error, getSearchVideoInfo, can not get info"); } return searchVideoInfos;}
"code": 1,"data": 0,"albumIdList": [ { "totalidnum": 2000,"idlist": [ "319281600" ] } ],"albumArray": { "319281600": { "_as": "","_blk": 0,"_cid": 1,"_ct": "2014-10-10 17:55:06","_da": "","_dl": 0,"_dn": "7296","_id": 319281600,"_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_120_160.jpg","_ip": 1,"_ma": "","_pc": 2,"_pid": 0,"_reseftv": 959,"_t": "末代独裁","_tvct": 1,"_tvs": 1,"_vt": 0,"a_av": 1,"a_pro": "","bpt": "0","clm": "","cn_year": "0","co_album_id": "0","ctype": 0,"desc": "","down": 0,"down2": "0","drm": 0,"fst_time": "2014-10-16","h1_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_180_236.jpg","h2_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_195_260.jpg","is_h": 0,"is_n": 0,"is_zb": 0,"k_word": "","language": 0,"live_center": 0,"live_start_time": 0,"live_stop_time": 0,"logo": 1,"m_av": 1,"p_av": 1,"p_s": 0,"p_s_1": 0,"p_s_4": 0,"p_s_8": 0,"qiyi_pro": 0,"qiyi_year": "0","qt_id": "1005722","s_TT": "","songname": "","t_pc": 1,"tag": "当代 美国 乡村 大片","tv_eftv": 1,"tv_pha": "","tv_pro": "","tv_ss": "","tvfcs": "雄心壮志背后的真相","up": 0,"up2": "0","upcl": "","v2_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_284_160.jpg","v3_img": "http://pic2.qiyipic.com/image/20141016/19/ca/v_108628048_m_601_m1_480_270.jpg","vv": "1","year": "2007","tv_id": "0","vv_p": 0,"vv_f": 2,"vv_m": 0,"_sc": 8 } },"changeAlbum": null,"category": null,"before": "2~4~1~7~3","latest_push_id": "655","up_tm": "1413441370874","recommend_attach": "","preset_keys": null,"category_group": null,"exp_ts": 120,"stfile_path": "/data/view/online5/0/1/2.1.8.5.1.txt"}从上面的例子可以很清晰的看出JSON是如何展示一个电影的数据的,当然这是JSON格式化之后的数据。JSON的元数据是不便于阅读的。
private String createJson() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("intKey", 123); jsonObject.put("doubleKey", 10.1); jsonObject.put("longKey", 666666666); jsonObject.put("stringKey", "lalala"); jsonObject.put("booleanKey", true); JSONArray jsonArray = new JSONArray(); jsonArray.put(0, 111); jsonArray.put("second"); jsonObject.put("arrayKey", jsonArray); JSONObject innerJsonObject = new JSONObject(); innerJsonObject.put("innerStr", "inner"); jsonObject.put("innerObjectKey", innerJsonObject); Log.e("Json", jsonObject.toString()); return jsonObject.toString();}其输出结果如下所示:
{"intKey":123, "doubleKey":10.1, "longKey":666666666, "stringKey":"lalala", "booleanKey":true, "arrayKey":[111,"second"], "innerObjectKey":{"innerStr":"inner"}}<3>. 如何解析JSON?
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, url, null,new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) {try { MyLog.d(TAG, "response=" + response); parseiQiyiInterfaceResponse(response);} catch (Exception e) { e.printStackTrace();} }}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) {/* * if (error instanceof NetworkError) { } else if (error * instanceof ClientError) { } else if (error instanceof * ServerError) { } else if (error instanceof * AuthFailureError) { } else if (error instanceof * ParseError) { } else if (error instanceof * NoConnectionError) { } else if (error instanceof * TimeoutError) { } */MyLog.e(TAG, "onErrorResponse, error=" + error); }}) { @Override public Map<String, String> getHeaders() throws AuthFailureError {HashMap<String, String> headers = new HashMap<String, String>();headers.put("t", iQiyiInterface.getEncryptTimestamp());headers.put("sign", iQiyiInterface.getSign());return headers; }};第二步,获取到对应的对应的JSONObject数据:
public void getJsonObjectString(String url) { mQueue = VideoApplication.getInstance().getRequestQueue(); JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) { MyLog.e(TAG, "response = " + response.toString()); JSONArray jsonArray = null; JSONObject jsonObject = null; try {jsonObject = response.getJSONObject("response");jsonArray = jsonObject.getJSONObject("result").getJSONArray("album"); } catch (JSONException e) {e.printStackTrace(); } if (jsonArray == null) {return; } mChannelList = VideoUtils.parseVideoJsonArray(jsonArray); if (isLoading) {isLoading = false;if (mIsGrid) { mChannelGridAdapter.appendChannelVideoInfo(mChannelList);} else { mChannelListAdapter.appendChannelVideoInfo(mChannelList);} } else {if (mIsGrid) { mChannelGridAdapter.setChannelVideoInfo(mChannelList); showOppoGrid();} else { mChannelListAdapter.setChannelVideoInfo(mChannelList); showOppoList();} }} }, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) { MyLog.e(TAG, "error = " + error);} }); jsObjRequest.setTag(TAG); jsObjRequest.setShouldCache(true); mQueue.add(jsObjRequest); mQueue.start();}获取到JSON Object之后,就对这个JSONObject进行解析:
private ArrayList<VideoConstant> parseVideoAlbumJsonObject(JSONObject albumJSONObject, ArrayList<Integer> albumIdJSONArrayList) { MyLog.d(TAG, "parseVideoAlbumJsonObject, length=" + albumJSONObject.length()); if (albumJSONObject.length() < 1) {return null; } ArrayList<VideoConstant> videos = new ArrayList<VideoConstant>(); try {for (int index = 0; index < albumJSONObject.length(); index++) { VideoConstant video = new VideoConstant(); JSONObject itemJsonObject; itemJsonObject = albumJSONObject.getJSONObject(albumIdJSONArrayList.get(index) .toString()); MyLog.d(TAG, "string=" + albumIdJSONArrayList.get(index).toString()); video.mAlbumId = itemJsonObject.optString(InterfaceParameterName.ID); video.mAtitle = itemJsonObject.optString(InterfaceParameterName.TITLE); video.mEpisodeCount = itemJsonObject.optString(InterfaceParameterName.UPDATE_SET); video.mTvSets = itemJsonObject.optString(InterfaceParameterName.TV_SETS); video.mDesc = itemJsonObject.optString(InterfaceParameterName.DESCRIPTION); video.mCid = itemJsonObject.optString(InterfaceParameterName.CATEGORY_ID); video.mImg = itemJsonObject.optString(InterfaceParameterName.IMG); video.mHighimg = itemJsonObject .optString(InterfaceParameterName.HIGH_RESO_PORT_IMG); video.mHoriImg = itemJsonObject .optString(InterfaceParameterName.HIGH_RESO_HORI_IMG); video.mScore = itemJsonObject.optString(InterfaceParameterName.SCORE); video.mMainActors = itemJsonObject.optString(InterfaceParameterName.MAIN_ACTOR); video.mCreateTime = itemJsonObject.optString(InterfaceParameterName.CREATE_TIME); video.mDuration = itemJsonObject.optString(InterfaceParameterName.DURATION); video.mTag = itemJsonObject.optString(InterfaceParameterName.TAG); MyLog.d(TAG, "id=" + video.mAlbumId + ",title=" + video.mAlbumTitle + ",img=" + video.mHighimg + ",tvsets=" + video.mTvSets); videos.add(video);} } catch (JSONException e) {e.printStackTrace(); } return videos;}<4>. Android JSON解析库
<student name="John" age="10"/>但如个某个 value 也是 object,那么就不可以当作attribute:
<student name="John" age="10"> <address><country>China</country><province>Guang Dong</province><city>...</city><district>...</district>... </address></student>那么,什么时候用element,什么时候用attribute,就已经是一个问题了。
{ "name": "John", "age" : 10, "address" : {"country" : "China","province" : "Guang Dong","city" : "..","district" : "..",... }}One More Thing…