【问题标题】:Webserver to android XML parsingWebserver 到 android XML 解析
【发布时间】:2018-01-04 17:44:43
【问题描述】:

我的 dot-net Web 服务器正在返回一个 XML。 我想在安卓应用中显示数据。

如何进行?

我有一个 SOAP 类,它获取 XML 作为响应并返回响应。如何在列表视图中解析该响应?

public String getAllDetails() {       
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    // Create the envelop.Envelop will be used to send the request
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
            SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    // Says that the soap webservice is a .Net service
    envelope.dotNet = true;
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
    String s = "";       
    androidHttpTransport.debug=true;
    androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
    try {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapPrimitive response = (SoapPrimitive) envelope.getResponse(); 
        s = response.toString();           
        Log.d("Converter", response.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return s;
}

【问题讨论】:

    标签: android xml parsing webserver


    【解决方案1】:

    您将需要创建一个 XMLParser.java 文件,该文件将使您能够解析您的 XML。然后使用相应的方法解析您的响应 XML 输出并将它们显示为 ListView、GridView、CardView 等。请参阅下面的代码,在解析 XML 时总是对我有用。

    //--------------------------------------------------------------
    //** XML Output
    //--------------------------------------------------------------
    
    <?xml version="1.0" encoding="UTF-8"?>
    <menu>
        <item>
            <id>1</id>
            <name>Manchester United</name>
        </item>
        <item>
            <id>2</id>
            <name>Barcelona</name>
        </item>
        <item>
            <id>3</id>
            <name>Real Madrid</name>
        </item>
        <item>
            <id>4</id>
            <name>Arsenal</name>
        </item>
    </menu>
    
    //--------------------------------------------------------------
    //** list_item.xml
    //--------------------------------------------------------------
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
        <LinearLayout 
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
        <TextView 
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#dc6800"
            android:textSize="16sp"
            android:textStyle="bold"
            android:paddingTop="6dip"
            android:paddingBottom="2dip" />
    
        </LinearLayout>
    
    </LinearLayout>
    
    //--------------------------------------------------------------
    //** main.xml
    //--------------------------------------------------------------
    
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">
    
        <ListView android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    
    
    //--------------------------------------------------------------
    //** XMLParser.java
    //--------------------------------------------------------------
    
    public class XMLParser {
    
        // constructor
        public XMLParser() {
    
        }
    
        /**
         * Getting XML from URL making HTTP request
         * @param url string
         * */
        public String getXmlFromUrl(String url) {
            String xml = null;
    
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                xml = EntityUtils.toString(httpEntity);
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // return XML
            return xml;
        }
    
        /**
         * Getting XML DOM element
         * @param XML string
         * */
        public Document getDomElement(String xml){
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            try {
    
                DocumentBuilder db = dbf.newDocumentBuilder();
    
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);
    
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
    
            return doc;
        }
    
        /** Getting node value
         * @param elem element
         */
        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 "";
        }
    
        /**
         * Getting node value
         * @param Element node
         * @param key string
         * */
        public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }
    }
    
    //--------------------------------------------------------------
    //** MainActivity.java
    //--------------------------------------------------------------
    
    public class MainActivity extends ListActivity {
    
        // All static variables
        static final String URL = "http://api.foo.foo/foo/?format=xml"; // Your XML output
        // XML node keys
        static final String KEY_ITEM = "item"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_NAME = "name";
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    
            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // 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>();
                Element e = (Element) nl.item(i);
                // 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));
    
                // adding HashList to ArrayList
                menuItems.add(map);
            }
    
            // Adding menuItems to ListView
            ListAdapter adapter = new SimpleAdapter(this, menuItems,
                    R.layout.list_item,
                    new String[] { KEY_NAME }, new int[] {
                    R.id.name });
    
            setListAdapter(adapter);
    
            // selecting single ListView item
            ListView lv = getListView();
    
            lv.setOnItemClickListener(new OnItemClickListener() {
    
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    // getting values from selected ListItem
                    String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                }
            });
        }
    }
    

    【讨论】:

    • 这不起作用,首先 defaulthttpclient 没有解析,但是当我解决它时,类上有一个删除线,然后网络部分应该在 asyntask 上完成,因为应用程序崩溃并且 logcat 说android.os.NetworkOnMainThreadException。你能推荐点别的吗
    • 它对我有用...只要确保您的 XML 作为 URL 返回并像我上面的示例一样解析它。
    • 我的 sdk 版本是更新版本..所以它不工作..异步任务会这样做..然后检查它
    猜你喜欢
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2012-05-21
    • 2017-03-22
    • 2012-01-12
    相关资源
    最近更新 更多