android操作xml

Android操作xml封装后的类,包括创建xml和读xml。

[java]  view plain  copy
  1. public class XmlParserUtil  
  2. {  
  3.     //创建xml文件   
  4.     public static void createXmlFile(final String xmlPath)  
  5.     {   
  6.         File xmlFile = new File(xmlPath);   
  7.         FileOutputStream fileOPStream = null;   
  8.         try  
  9.         {   
  10.             fileOPStream = new FileOutputStream(xmlFile);   
  11.         }  
  12.         catch (FileNotFoundException e)   
  13.         {   
  14.             Log.e("FileNotFoundException""can't create FileOutputStream");   
  15.         }   
  16.   
  17.         XmlSerializer serializer = Xml.newSerializer();   
  18.         try  
  19.         {   
  20.             serializer.setOutput(fileOPStream,"UTF-8");   
  21.             serializer.startDocument(nulltrue);   
  22.             serializer.startTag(null"books");   
  23.   
  24.             for(int i = 0; i < 5; i ++)  
  25.             {   
  26.                 serializer.startTag(null"book");   
  27.                 serializer.startTag(null"bookname");   
  28.                 serializer.text("Android教程" + i);   
  29.                 serializer.endTag(null"bookname");   
  30.                 serializer.startTag(null"bookauthor");   
  31.                 serializer.text("Frankie" + i);   
  32.                 serializer.endTag(null"bookauthor");   
  33.                 serializer.endTag(null"book");   
  34.             }   
  35.   
  36.             serializer.endTag(null"books");   
  37.             serializer.endDocument();   
  38.   
  39.             serializer.flush();   
  40.             fileOPStream.close();   
  41.         }   
  42.         catch (Exception e)   
  43.         {   
  44.             Log.e("XmlParserUtil","error occurred while creating xml file");   
  45.         }   
  46.         Toast.makeText(getApplicationContext(), "创建xml文件成功!", Toast.LENGTH_SHORT).show();   
  47.     }   
  48.   
  49.     /** dom解析xml文件  
  50.     * xmlPath xml的路径 
  51.     */  
  52.     public static void domParseXML(final String xmlPath)  
  53.     {   
  54.         File file = new File(xmlPath);   
  55.         if(!file.exists()||file.isDirectory())  
  56.         {  
  57.             Log.e("domParseXML""file not exists");  
  58.             return;  
  59.         }  
  60.               
  61.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
  62.         DocumentBuilder db = null;   
  63.         try   
  64.         {   
  65.             db = dbf.newDocumentBuilder();   
  66.         }   
  67.         catch (ParserConfigurationException e)   
  68.         {   
  69.             e.printStackTrace();   
  70.         }   
  71.   
  72.         Document doc = null;   
  73.         try   
  74.         {   
  75.             doc = db.parse(file);   
  76.         }   
  77.         catch (SAXException e)   
  78.         {   
  79.             e.printStackTrace();   
  80.         }   
  81.         catch (IOException e)  
  82.         {   
  83.             e.printStackTrace();   
  84.         }   
  85.   
  86.         Element root = doc.getDocumentElement();   
  87.         NodeList books = root.getElementsByTagName("book");   
  88.         String res = "本结果是通过dom解析:" + "\n";   
  89.   
  90.         for(int i = 0; i < books.getLength();i++)  
  91.         {   
  92.             Element book = (Element)books.item(i);   
  93.             Element bookname = (Element)book.getElementsByTagName("bookname").item(0);   
  94.             Element bookauthor = (Element)book.getElementsByTagName("bookauthor").item(0);   
  95.             res += "书名: " + bookname.getFirstChild().getNodeValue() + " " +   
  96.                     "作者: " + bookauthor.getFirstChild().getNodeValue() + "\n";   
  97.         }   
  98.   
  99.     }   
  100.   
  101.     /** xmlPullParser解析xml文件  
  102.     * xmlPath xml的路径 
  103.     */  
  104.     public static void xmlPullParseXML(final String xmlPath)  
  105.     {   
  106.         String res = "本结果是通过XmlPullParse解析:" + "\n";   
  107.         try  
  108.         {   
  109.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();   
  110.             XmlPullParser xmlPullParser = factory.newPullParser();   
  111.             try  
  112.             {  
  113.                 xmlPullParser.setInput(new StringReader(bufferedReaderFile(xmlPath)));  
  114.             }  
  115.             catch (Exception e)   
  116.             {  
  117.                 Log.e("xmlPullParseXML", e.toString());  
  118.             }  
  119.   
  120.             int eventType = xmlPullParser.getEventType();   
  121.             try  
  122.             {   
  123.                 while (eventType != XmlPullParser.END_DOCUMENT)  
  124.                 {   
  125.                     String nodeName = xmlPullParser.getName();   
  126.                     switch (eventType)  
  127.                     {   
  128.                     case XmlPullParser.START_TAG:   
  129.                         if("bookname".equals(nodeName))  
  130.                         {   
  131.                             res += "书名: " + xmlPullParser.nextText() + " ";   
  132.                         }  
  133.                         else if("bookauthor".equals(nodeName))  
  134.                         {   
  135.                             res += "作者: " + xmlPullParser.nextText() + "\n";   
  136.                         }   
  137.                         break;   
  138.   
  139.                     default:   
  140.                         break;   
  141.                     }   
  142.                     eventType = xmlPullParser.next();   
  143.                 }   
  144.             }   
  145.             catch (IOException e)  
  146.             {   
  147.                 e.printStackTrace();   
  148.             }   
  149.         }   
  150.         catch (XmlPullParserException e)  
  151.         {   
  152.             e.printStackTrace();   
  153.         }   
  154.     }   
  155.       
  156.     //从sd卡中读取xml文件的内容  
  157.     private String bufferedReaderFile(final String path) throws IOException  
  158.     {  
  159.         File file=new File(path);  
  160.         if(!file.exists()||file.isDirectory())  
  161.             throw new FileNotFoundException();  
  162.   
  163.         BufferedReader br=new BufferedReader(new FileReader(file));  
  164.         String temp=null;  
  165.         StringBuffer sb=new StringBuffer();  
  166.         temp=br.readLine();  
  167.         while(temp!=null)  
  168.         {  
  169.             sb.append(temp+" ");  
  170.             temp=br.readLine();  
  171.         }  
  172.         br.close();  
  173.   
  174.         return sb.toString();  
  175.     }  
  176.   
  177. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
xml文件操作 public class XmlUtils { /** * 获取Document对象。根据xml文件的名字获取Document对象。 * * @param file * 要获取对象的xml文件全路径。 * @return 返回获取到的Document对象。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 * @exception NullPointerException * 如果file为空时,抛出此异常。 */ public static Document parseForDoc(final String file) throws SAXException, IOException, SecurityException, NullPointerException, ParserConfigurationException { return XmlUtils.parseForDoc(new FileInputStream(file)); } /** * 将一个xml字符串解析成Document对象。 * * @param xmlStr * 要被解析的xml字符串。 * @param encoding * 字符串的编码。 * @return 返回解析后的Document对象。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 */ public static Document parseForDoc(String xmlStr, String encoding) throws SAXException, IOException, ParserConfigurationException { if (xmlStr == null) { xmlStr = ""; } ByteArrayInputStream byteInputStream = new ByteArrayInputStream( xmlStr.getBytes(encoding)); return XmlUtils.parseForDoc(byteInputStream); } /** * 获取Document对象。根据字节输入流获取一个Document对象。 * * @param is * 获取对象的字节输入流。 * @return 返回获取到的Document对象。如果出现异常,返回null。 * @throws IOException * 如果发生任何 IO 错误时抛出此异常。 * @throws SAXException * 如果发生任何解析错误时抛出此异常。 * @throws ParserConfigurationException * 如果无法创建满足所请求配置的 DocumentBuilder,将抛出该异常。 * @exception IllegalArgumentException * 当 is 为 null 时抛出此异常。 */ public static Document parseForDoc(final InputStream is) throws SAXException, IOException, ParserConfigurationException, IllegalArgumentException { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(is); } finally { is.close(); } } /** * 通过xpath表达式解析某个xml节点。 * * @param obj * 要被解析的xml节点对象。 * @param xPath * xpath表达式。 * @param qName * 被解析的目标类型。 * @return 返回解析后的对象。 * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ private static Object parseByXpath(final Object obj, final String xPath, QName qName) throws NullPointerException, RuntimeException, XPathExpressionException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath path = xpathFactory.newXPath(); return path.evaluate(xPath, obj, qName); } /** * 通过XPath表达式获取单个节点。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static Node parseForNode(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (Node) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODE); } /** * 通过XPath表达式获取某个xml节点的字符串值。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点的字符串值。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static String parseForString(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (String) XmlUtils .parseByXpath(obj, xPath, XPathConstants.STRING); } /** * 通过XPath表达式获取某个xml节点的布尔值。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的节点的布尔值。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static Boolean parseForBoolean(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { return (Boolean) XmlUtils.parseByXpath(obj, xPath, XPathConstants.BOOLEAN); } /** * 通过XPath表达式获取Node列表。 * * @param obj * 要被解析的對象。 * @param xPath * XPath表达式。 * @return 返回获取到的Node列表。 * * @throws XPathExpressionException * 如果不能计算 expression。 * * @exception RuntimeException * 创建默认对象模型的 XPathFactory 遇到故障时。 * @exception NullPointerException * 如果xPath为空时抛出时异常。 */ public static List parseForNodeList(final Object obj, final String xPath) throws NullPointerException, RuntimeException, XPathExpressionException { List lists = new ArrayList(); NodeList nList = (NodeList) XmlUtils.parseByXpath(obj, xPath, XPathConstants.NODESET); if (nList != null) { for (int i = 0; i < nList.getLength(); i++) { lists.add(nList.item(i)); } } return lists; } /** * 获取节点的制定属性。 * * @param node * 节点。 * @param attrName * 属性名。 * @return 返回获取到的属性值。如果找不到相关的 * */ public static String getAttribute(final Object node, final String attrName) { String result = ""; if ((node != null) && (node instanceof Node)) { if (((Node) node).getNodeType() == Node.ELEMENT_NODE) { result = ((Element) node).getAttribute(attrName); } else { // 遍历整个xml某节点指定的属性 NamedNodeMap attrs = ((Node) node).getAttributes(); if ((attrs.getLength() > 0) && (attrs != null)) { Node attr = attrs.getNamedItem(attrName); result = attr.getNodeValue(); } } } return result; } /** * 使用新节点替换原来的旧节点。 * * @param oldNode * 要被替换的旧节点。 * @param newNode * * 替换后的新节点。 * @exception DOMException * 如果此节点为不允许 * newNode节点类型的子节点的类型;或者如果要放入的节点为此节点的一个祖先或此节点本身;或者如果此节点为 * Document 类型且替换操作的结果将第二个 DocumentType 或 Element 添加到 * Document 上。 WRONG_DOCUMENT_ERR: 如果 newChild * 是从不同的文档创建的,不是从创建此节点的文档创建的,则引发此异常。 * NO_MODIFICATION_ALLOWED_ERR: 如果此节点或新节点的父节点为只读的,则引发此异常。 * NOT_FOUND_ERR: 如果 oldChild 不是此节点的子节点,则引发此异常。 * NOT_SUPPORTED_ERR: 如果此节点为 Document 类型,则如果 DOM 实现不支持替换 * DocumentType 子节点或 Element 子节点,则可能引发此异常。 */ public static void replaceNode(Node oldNode, Node newNode) { if ((oldNode != null) && (newNode != null)) { oldNode.getParentNode().replaceChild(newNode, oldNode); } } /** * 将Document输出到指定的文件中。 * * @param fileName * 文件名。 * @param node * 要保存的对象。 * @param encoding * 保存的编码。 * @throws FileNotFoundException * 指定的文件名不存在时,抛出此异常。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 */ public static void saveXml(final String fileName, final Node node, String encoding) throws FileNotFoundException, TransformerException { XmlUtils.writeXml(new FileOutputStream(fileName), node, encoding); } /** * 将Document输出成字符串的形式。 * * @param node * Node对象。 * @param encoding * 字符串的编码。 * @return 返回输出成的字符串。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 * @throws UnsupportedEncodingException * 指定的字符串编码不支持时,抛出此异常。 */ public static String nodeToString(Node node, String encoding) throws TransformerException, UnsupportedEncodingException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XmlUtils.writeXml(outputStream, node, encoding); return outputStream.toString(encoding); } /** * 将指定的Node写到指定的OutputStream流中。 * * @param encoding * 编码。 * @param os * OutputStream流。 * @param node * Node节点。 * @throws TransformerException * 如果转换过程中发生不可恢复的错误时,抛出此异常。 */ private static void writeXml(OutputStream os, Node node, String encoding) throws TransformerException { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); DOMSource source = new DOMSource(); source.setNode(node); StreamResult result = new StreamResult(); result.setOutputStream(os); transformer.transform(source, result); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值