国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android中XML的基本操作(增、刪、改、查)

2019-10-23 18:31:04
字體:
來源:轉載
供稿:網友

Android中XML的一些操作

解析類:

// 構造方法   public XMLParser() {    }    /**    * 從URL獲取XML使HTTP請求    *    * @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, "UTF-8");     } catch (UnsupportedEncodingException e) {       e.printStackTrace();     } catch (ClientProtocolException e) {       e.printStackTrace();     } catch (IOException e) {       e.printStackTrace();     }     return xml;   }    /**    * 獲取XML DOM元素    *    * @param XML    *      string    * */   public Document getDomElement(InputStream is) {     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;   }    public Document getDomDocumentUpdate(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;   }    /**    * 獲取節點值    *    * @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 "";   }    /**    * 獲取節點值    *    * @param Element    *      node    * @param key    *      string    * */   public String getValue(Element item, String str) {     NodeList n = item.getElementsByTagName(str);     return this.getElementValue(n.item(0));   }   //XML文件有更新后,調用此方法   public void output(Document node, String filename) {     TransformerFactory transFactory = TransformerFactory.newInstance();     try {       Transformer transformer = transFactory.newTransformer();       // 設置各種輸出屬性       transformer.setOutputProperty("encoding", "UTF-8");       transformer.setOutputProperty("indent", "yes");       DOMSource source = new DOMSource(node);       // 將待轉換輸出節點賦值給DOM源模型的持有者(holder)       // /source.setNode(node);       StreamResult result = new StreamResult();       if (filename == null) {         // 設置標準輸出流為transformer的底層輸出目標         result.setOutputStream(System.out);       } else {         result.setOutputStream(new FileOutputStream(filename));       }       // 執行轉換從源模型到控制臺輸出流       transformer.transform(source, result);     } catch (TransformerConfigurationException e) {       e.printStackTrace();     } catch (TransformerException e) {       e.printStackTrace();     } catch (FileNotFoundException e) {       e.printStackTrace();     }   }    public String writeXml() {     XmlSerializer xml = Xml.newSerializer();     StringWriter writer = new StringWriter();     try {       xml.setOutput(writer);       xml.startDocument("UTF-8", true);       xml.startTag("", "blog");        xml.startTag("", "message");       xml.attribute("", "name", "xia");       xml.startTag("", "age");       xml.text("22");       xml.endTag("", "age");        xml.startTag("", "hobby");       xml.text("play");       xml.endTag("", "hobby");        xml.startTag("", "hight");       xml.text("165");       xml.endTag("", "hight");       xml.endTag("", "message");        xml.startTag("", "message");       xml.attribute("", "name", "chen");       xml.startTag("", "age");       xml.text("21");       xml.endTag("", "age");        xml.startTag("", "hobby");       xml.text("swin");       xml.endTag("", "hobby");        xml.startTag("", "hight");       xml.text("170");       xml.endTag("", "hight");       xml.endTag("", "message");        xml.endTag("", "blog");       xml.endDocument();      } catch (Exception e) {       throw new RuntimeException(e);      }      return writer.toString();   }        public boolean Write(String Filepath, String txt) {     FileOutputStream fos = null;     if (Environment.getExternalStorageState() != null) {// 這個方法在試探終端是否有sdcard!       File path = new File("sdcard/test");// 創建目錄       File f = new File(Filepath);// 創建文件       if (!path.exists()) {// 目錄不存在返回false         path.mkdirs();// 創建一個目錄       }       if (!f.exists()) {// 文件不存在返回false         try {           f.createNewFile();           fos = new FileOutputStream(f);           fos.write((txt).getBytes("UTF-8"));           fos.close();         } catch (IOException e) {           // TODO Auto-generated catch block           e.printStackTrace();         }// 創建一個文件       }      }     return true;   }    private static XMLParser uniqueInstance = null;    public static XMLParser getInstance() {     if (uniqueInstance == null) {       uniqueInstance = new XMLParser();     }     return uniqueInstance;   } } 

上面的這個類中用了單例!分別定義了XML的創建,獲取XML的節點值,更新后執行的操作!

MainActivity:

public class MainActivity extends Activity {   public static final String XMLPath = "sdcard/test/message.xml";   private Button create = null;    @Override   public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     create = (Button) findViewById(R.id.create);   }    // 自動創建XML   private void createXml() {     // sdcard/test/message.xml     XMLParser.getInstance().Write(XMLPath,         XMLParser.getInstance().writeXml());   }    // 遍歷節點,找到特定節點并進行更換!   private void selectNode() {     Document document = null;     try {       FileInputStream fin = new FileInputStream(XMLPath);       document = XMLParser.getInstance().getDomElement(fin);       Node root = document.getDocumentElement();       if (root.hasChildNodes()) {         NodeList ftpnodes = root.getChildNodes();         Log.e("eee", root.getNodeName());// 根節點 blog          for (int i = 0; i < ftpnodes.getLength(); i++) {           NodeList ftplist = ftpnodes.item(i).getChildNodes();           Node su = ftpnodes.item(i);           Log.e("eee", su.getNodeName());// message           Element e = (Element) ftpnodes.item(i);           Log.e("eee", e.getAttribute("name"));// message= xia           for (int k = 0; k < ftplist.getLength(); k++) {             Node subnode = ftplist.item(k);             Log.e("eee",                 " subnode.getNodeName()"                     + subnode.getNodeName());             Log.e("eee",                 "subnode.getNodeType()" + subnode.getNodeType());             Log.e("eee", subnode.getFirstChild().getNodeValue());             if (subnode.getNodeType() == Node.ELEMENT_NODE                 && subnode.getNodeName().equals("hight")) {               subnode.getFirstChild().setNodeValue("175");               XMLParser.getInstance().output(document, XMLPath);             }           }         }       }      } catch (Exception e) {      }   }    // 添加一個新的根節點   private void insertNode() {     Document document = null;     try {       FileInputStream fin = new FileInputStream(XMLPath);       document = XMLParser.getInstance().getDomElement(fin);       // 插入根節點message       /**        * <message name="wang"> <hight>180</hight> <age>22</age> </message>        *        * */       Element eltStu = document.createElement("message");       Element eltName = document.createElement("hight");       Element eltAge = document.createElement("age");       Attr attr = document.createAttribute("name");       attr.setValue("wang");       Text txtName = document.createTextNode("180");       Text txtAge = document.createTextNode("22");       eltName.appendChild(txtName);       eltAge.appendChild(txtAge);       eltStu.appendChild(eltName);       eltStu.appendChild(eltAge);       eltStu.setAttributeNode(attr);       Element eltRoot = document.getDocumentElement();       eltRoot.appendChild(eltStu);       XMLParser.getInstance().output(document, XMLPath);     } catch (Exception e) {      }   }    private void instertChildNode() {     Document document = null;     try {       FileInputStream fin = new FileInputStream(XMLPath);       document = XMLParser.getInstance().getDomElement(fin);       // 在某個根節點下面添加節點       /**        * <message name="wang"> <hight>180</hight> <age>22</age>        * <hobby>music</hobby>//這句是新添加的 </message>        *        * */       Node root = document.getDocumentElement();       NodeList ftpnodes = root.getChildNodes();       Log.e("eee", root.getNodeName());// 根節點 blog       NodeList ftplist = ftpnodes.item(1).getChildNodes();       Node su = ftpnodes.item(1);       Log.e("eee", su.getNodeName());// message       Element e = (Element) ftpnodes.item(5);// message= wang       Log.e("eee", e.getAttribute("name"));       if (e.getAttribute("name").equals("wang")) {         Element elthoby = document.createElement("hobby");         Text txthoby = document.createTextNode("music");         elthoby.appendChild(txthoby);         Node stNode = document.getElementsByTagName("message").item(2);         stNode.appendChild(elthoby);       }       XMLParser.getInstance().output(document, XMLPath);     } catch (Exception e) {     }   }    private void removeNode() {     Document document = null;     try {       FileInputStream fin = new FileInputStream(XMLPath);       document = XMLParser.getInstance().getDomElement(fin);       // 刪除blog下的message的0個節點       NodeList nl = document.getElementsByTagName("message");       Node nodeDel = (Element) nl.item(0);       nodeDel.getParentNode().removeChild(nodeDel);       XMLParser.getInstance().output(document, XMLPath);     } catch (Exception e) {     }   }    @Override   protected void onDestroy() {     super.onDestroy();   } } 

最后記得添加讀寫SDcard的權限!

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜都市| 施甸县| 汉源县| 大英县| 溆浦县| 廉江市| 庄浪县| 永城市| 凤冈县| 林口县| 根河市| 庄浪县| 腾冲县| 吉林省| 大荔县| 梓潼县| 甘谷县| 共和县| 弥渡县| 德清县| 广丰县| 龙泉市| 虞城县| 定日县| 桓仁| 石楼县| 合山市| 炎陵县| 台中市| 乌拉特后旗| 兴城市| 崇阳县| 聂荣县| 扶绥县| 潼南县| 澜沧| 荔波县| 乌拉特前旗| 惠东县| 翁牛特旗| 瑞丽市|