Android中XML的基本操作(增、删、改、查)
Android中XML的一些操作
解析类:
//构造方法
publicXMLParser(){
}
/**
*从URL获取XML使HTTP请求
*
*@paramurl
*string
**/
publicStringgetXmlFromUrl(Stringurl){
Stringxml=null;
try{
//defaultHttpClient
DefaultHttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
HttpResponsehttpResponse=httpClient.execute(httpPost);
HttpEntityhttpEntity=httpResponse.getEntity();
xml=EntityUtils.toString(httpEntity,"UTF-8");
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(ClientProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
returnxml;
}
/**
*获取XMLDOM元素
*
*@paramXML
*string
**/
publicDocumentgetDomElement(InputStreamis){
Documentdoc=null;
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
try{
DocumentBuilderdb=dbf.newDocumentBuilder();
//InputSourceis=newInputSource();
//is.setCharacterStream(newStringReader(xml));
doc=db.parse(is);
}catch(ParserConfigurationExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}catch(SAXExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}catch(IOExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}
returndoc;
}
publicDocumentgetDomDocumentUpdate(Stringxml){
Documentdoc=null;
DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
try{
DocumentBuilderdb=dbf.newDocumentBuilder();
InputSourceis=newInputSource();
is.setCharacterStream(newStringReader(xml));
doc=db.parse(is);
}catch(ParserConfigurationExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}catch(SAXExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}catch(IOExceptione){
Log.e("Error:",e.getMessage());
returnnull;
}
returndoc;
}
/**
*获取节点值
*
*@paramelem
*element
*/
publicfinalStringgetElementValue(Nodeelem){
Nodechild;
if(elem!=null){
if(elem.hasChildNodes()){
for(child=elem.getFirstChild();child!=null;child=child
.getNextSibling()){
if(child.getNodeType()==Node.TEXT_NODE){
returnchild.getNodeValue();
}
}
}
}
return"";
}
/**
*获取节点值
*
*@paramElement
*node
*@paramkey
*string
**/
publicStringgetValue(Elementitem,Stringstr){
NodeListn=item.getElementsByTagName(str);
returnthis.getElementValue(n.item(0));
}
//XML文件有更新后,调用此方法
publicvoidoutput(Documentnode,Stringfilename){
TransformerFactorytransFactory=TransformerFactory.newInstance();
try{
Transformertransformer=transFactory.newTransformer();
//设置各种输出属性
transformer.setOutputProperty("encoding","UTF-8");
transformer.setOutputProperty("indent","yes");
DOMSourcesource=newDOMSource(node);
//将待转换输出节点赋值给DOM源模型的持有者(holder)
///source.setNode(node);
StreamResultresult=newStreamResult();
if(filename==null){
//设置标准输出流为transformer的底层输出目标
result.setOutputStream(System.out);
}else{
result.setOutputStream(newFileOutputStream(filename));
}
//执行转换从源模型到控制台输出流
transformer.transform(source,result);
}catch(TransformerConfigurationExceptione){
e.printStackTrace();
}catch(TransformerExceptione){
e.printStackTrace();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
}
publicStringwriteXml(){
XmlSerializerxml=Xml.newSerializer();
StringWriterwriter=newStringWriter();
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(Exceptione){
thrownewRuntimeException(e);
}
returnwriter.toString();
}
publicbooleanWrite(StringFilepath,Stringtxt){
FileOutputStreamfos=null;
if(Environment.getExternalStorageState()!=null){//这个方法在试探终端是否有sdcard!
Filepath=newFile("sdcard/test");//创建目录
Filef=newFile(Filepath);//创建文件
if(!path.exists()){//目录不存在返回false
path.mkdirs();//创建一个目录
}
if(!f.exists()){//文件不存在返回false
try{
f.createNewFile();
fos=newFileOutputStream(f);
fos.write((txt).getBytes("UTF-8"));
fos.close();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}//创建一个文件
}
}
returntrue;
}
privatestaticXMLParseruniqueInstance=null;
publicstaticXMLParsergetInstance(){
if(uniqueInstance==null){
uniqueInstance=newXMLParser();
}
returnuniqueInstance;
}
}
上面的这个类中用了单例!分别定义了XML的创建,获取XML的节点值,更新后执行的操作!
MainActivity:
publicclassMainActivityextendsActivity{
publicstaticfinalStringXMLPath="sdcard/test/message.xml";
privateButtoncreate=null;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
create=(Button)findViewById(R.id.create);
}
//自动创建XML
privatevoidcreateXml(){
//sdcard/test/message.xml
XMLParser.getInstance().Write(XMLPath,
XMLParser.getInstance().writeXml());
}
//遍历节点,找到特定节点并进行更换!
privatevoidselectNode(){
Documentdocument=null;
try{
FileInputStreamfin=newFileInputStream(XMLPath);
document=XMLParser.getInstance().getDomElement(fin);
Noderoot=document.getDocumentElement();
if(root.hasChildNodes()){
NodeListftpnodes=root.getChildNodes();
Log.e("eee",root.getNodeName());//根节点blog
for(inti=0;i180 22
*
**/
ElementeltStu=document.createElement("message");
ElementeltName=document.createElement("hight");
ElementeltAge=document.createElement("age");
Attrattr=document.createAttribute("name");
attr.setValue("wang");
TexttxtName=document.createTextNode("180");
TexttxtAge=document.createTextNode("22");
eltName.appendChild(txtName);
eltAge.appendChild(txtAge);
eltStu.appendChild(eltName);
eltStu.appendChild(eltAge);
eltStu.setAttributeNode(attr);
ElementeltRoot=document.getDocumentElement();
eltRoot.appendChild(eltStu);
XMLParser.getInstance().output(document,XMLPath);
}catch(Exceptione){
}
}
privatevoidinstertChildNode(){
Documentdocument=null;
try{
FileInputStreamfin=newFileInputStream(XMLPath);
document=XMLParser.getInstance().getDomElement(fin);
//在某个根节点下面添加节点
/**
*180 22
*music //这句是新添加的
*
**/
Noderoot=document.getDocumentElement();
NodeListftpnodes=root.getChildNodes();
Log.e("eee",root.getNodeName());//根节点blog
NodeListftplist=ftpnodes.item(1).getChildNodes();
Nodesu=ftpnodes.item(1);
Log.e("eee",su.getNodeName());//message
Elemente=(Element)ftpnodes.item(5);//message=wang
Log.e("eee",e.getAttribute("name"));
if(e.getAttribute("name").equals("wang")){
Elementelthoby=document.createElement("hobby");
Texttxthoby=document.createTextNode("music");
elthoby.appendChild(txthoby);
NodestNode=document.getElementsByTagName("message").item(2);
stNode.appendChild(elthoby);
}
XMLParser.getInstance().output(document,XMLPath);
}catch(Exceptione){
}
}
privatevoidremoveNode(){
Documentdocument=null;
try{
FileInputStreamfin=newFileInputStream(XMLPath);
document=XMLParser.getInstance().getDomElement(fin);
//删除blog下的message的0个节点
NodeListnl=document.getElementsByTagName("message");
NodenodeDel=(Element)nl.item(0);
nodeDel.getParentNode().removeChild(nodeDel);
XMLParser.getInstance().output(document,XMLPath);
}catch(Exceptione){
}
}
@Override
protectedvoidonDestroy(){
super.onDestroy();
}
}
最后记得添加读写SDcard的权限!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!