サーバーからxmlを取得するために残りのWebサービスを使用しているアプリケーションを開発しています。サーバーから (xml 形式で) 応答を取得した後、Dom パーサーを使用してそれを文字列に解析しています。以下は、私の xml 応答のサンプル構造です。
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<rating>Gloves</rating>
</brand>
<categories>
<categorie Table >
<sourseUrl Chair>
<image available="true" height="400" width="400">
<serverURL http://abcd.xyzpqr.com/images/pi/89 /da/0c=121017011508&=3>
</serverURL>
</sourseUrl>
</categorie>
<relatedProducts >
<sometag ........>
<childtag1.........> </childtag1>
<childtag2.........>
<tag1.....>
<tag2.....>
</childtag2>
</sometag>
</relatedProducts>
..........
..........
..........
</categories>
以下は、HTTPリクエストを作成してXMLコンテンツを取得するための私のコードです
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpHost proxy = new HttpHost("45.28.19.345", 1234);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
HttpEntity httpEntity = httpResponse.getEntity();
xml = getASCIIContentFromEntity(httpEntity);</pre>
要素ノード名 public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); を渡すことによって、各 xml 子要素の値を取得します。this.getElementValue(n.item(0)); を返します。}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
解析されたxmlデータを取得する方法は次のとおりです。
String newxml = xml.toString();
Document doc = parser.getDomElement(newxml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
for(int k = 0; k < doc.getChildNodes().getLength(); k++) {
Element e = (Element) nl.item(k);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);</pre>
getDomElement(String xml) メソッドは
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
if(is != null){
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
このロジックを使用すると、単純な xml を取得できますが、上記のような複雑な xml は取得できません。そのネストされたxmlからデータを取得するアイデアを誰かが与えることができますか?