欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

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

时间:2021-02-15 10:21:14|栏目:Android代码|点击:

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 OpenGLES2.0等腰直角三角形和彩色的三角形(三)

栏    目:Android代码

下一篇:Android仿qq分组管理的第三方库

本文标题:Android中XML的基本操作(增、删、改、查)

本文地址:http://www.codeinn.net/misctech/63372.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有