Android反射修改xml,Android 解析、修改xml文件

一、DOM解析XML文件

public static void main(String[] args) {

File file = new File("d:\\WordChronos.xml");

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder docbuder;

try {

docbuder = dbf.newDocumentBuilder();

Document doc = docbuder.parse(file);

NodeList nl = doc.getElementsByTagName_r("Set");

for(int i = 0;i < nl.getLength();i ++){

doc.getElementsByTagName_r("Time1").item(0).getFirstChild().setNodeValue("2010-10-30");

String s1 = doc.getElementsByTagName_r("Time1").item(0).getFirstChild().getNodeValue();

String s2 = doc.getElementsByTagName_r("Time2").item(0).getFirstChild().getNodeValue();

String s3 = doc.getElementsByTagName_r("Time3").item(0).getFirstChild().getNodeValue();

String s4 = doc.getElementsByTagName_r("Music1").item(0).getFirstChild().getNodeValue();

System.out.println(s1 + ";" + s2 + ";" + s3 + ";" + s4);

}

} catch (ParserConfigurationException e) {

e.printStackTrace();

} catch (SAXException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

二、DOM4J解析XML文件

SAXReader reader = new SAXReader();

Document document;

try {

document = reader.read(new File("d:\\WordChronos.xml"));

Element root = ((org.dom4j.Document) document).getRootElement();

List worktimes = root.elements("Set");

for (Element worktime : worktimes) {

worktime.element("Time1").setText("07:00");

worktime.element("Time2").setText("08:00");

worktime.element("Time3").setText("09:00");

worktime.element("Music1").setText("我知道我爱你.mp3");

time1 = worktime.element("Time1").getText();

time2 = worktime.element("Time2").getText();

time3 = worktime.element("Time3").getText();

musicPath1 = worktime.element("Music1").getText();

System.out.println(time1+"\t"+time2+"\t"+time3+"\t"+musicPath1);

}

XMLWriter writer = new XMLWriter(new FileWriter("d:\\WordChronos.xml"));

writer.write(document);

writer.close();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (DocumentException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

三、Android自带的pull解析方式

********************************xml文件格式***************************************

0101

春节

0115

元宵节

0202

青龙节

。。。。。。。

**********************************************************************************

//解析XML文件

public List parser2(){

//引用资源中的xml文件,如下方式获取:

//XmlPullParser parser = this.getResources().getXml(R.xml.solarfeastfile);

//引用sdcard里面的xml文件,如下方式获取

XmlPullParser parser = Xml.newPullParser();

InputStream is = new FileInputStream(path);

parser.setInput(is,"utf-8");

try {

int eventType = parser.getEventType();

Message currentMessage = null;

boolean done = false;

while(eventType!= XmlPullParser.END_DOCUMENT && !done){

String name = null;

switch(eventType){

case XmlPullParser.START_DOCUMENT:

message2 = new ArrayList();

break;

case XmlPullParser.START_TAG:

name = parser.getName();

if(name.equalsIgnoreCase("Feast")){

currentMessage = new Message();

}else if(currentMessage != null){

if(name.equalsIgnoreCase("Date")){

currentMessage.setDate(parser.nextText());

}else if(name.equalsIgnoreCase("content")){

currentMessage.setContent(parser.nextText());

}

}

break;

case XmlPullParser.END_TAG:

name = parser.getName();

if(name.equalsIgnoreCase("Feast") && currentMessage != null){

message2.add(currentMessage);

}

break;

}

eventType = parser.next();

}

} catch (XmlPullParserException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return message2;

}

四、SAX引擎读取xml文件:

************************************xml文件格式*********************************

10

电脑

2067.25

20

微波炉

520

30

洗衣机

2400

********************************************************************************

1、继承DefaultHandler类,处理5个分析点的事件

public class XML2Product extends DefaultHandler{

private List products;

private Product product;

private StringBuffer buffer = new StringBuffer();

public List getProducts(){

return products;

}

@Override

public void characters(char[] ch, int start, int length) throws SAXException{

buffer.append(ch, start, length);

super.characters(ch, start, length);

}

@Override

public void endElement(String uri, String localName, String qName) throws SAXException{

if (localName.equals("product")){

products.add(product);

}else if (localName.equals("id")){

product.setId(Integer.parseInt(buffer.toString().trim()));

buffer.setLength(0);

}else if (localName.equals("name")){

product.setName(buffer.toString().trim());

buffer.setLength(0);

}else if (localName.equals("price")){

product.setPrice(Float.parseFloat(buffer.toString().trim()));

buffer.setLength(0);

}

super.endElement(uri, localName, qName);

}

@Override

public void startDocument() throws SAXException{

products = new ArrayList();

}

@Override

public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException{

if (localName.equals("product")){

product = new Product();

}

super.startElement(uri, localName, qName, attributes);

}

}

2、引用上面的类,将解析的内容显示出来

@Override

public void onFileItemClick(String filename){

try{

if (!filename.toLowerCase().endsWith("xml"))

return;

FileInputStream fis = new FileInputStream(filename);

XML2Product xml2Product = new XML2Product();

android.util.Xml.parse(fis, Xml.Encoding.UTF_8, xml2Product);

List products = xml2Product.getProducts();

String msg = "共" + products.size() + "个产品\n";

for (Product product : products){

msg += "id:" + product.getId() + " 产品名:" + product.getName() + " 价格:" + product.getPrice() + "\n";

}

new AlertDialog.Builder(this).setTitle("产品信息").setMessage(msg).setPositiveButton("关闭", null).show();

}

catch (Exception e){

}

}

  • 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、付费专栏及课程。

余额充值