栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

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

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Android中XML的一些操作

解析类:

// 构造方法 
  public XMLParser() { 
 
  } 
 
   
  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; 
  } 
 
   
  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; 
  } 
 
   
  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 ""; 
  } 
 
   
  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 
       
      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); 
      // 在某个根节点下面添加节点 
       
      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的权限!

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/158967.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号