您好,登錄后才能下訂單哦!
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的權限!
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。