黑马程序员--解析XML的几种方法

------- android培训java培训、期待与您交流! ----------


------DOM解析XML方法--------------

//取得DocmentBuilderFactory对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//取得DocmentBuilder对象
DocumentBuilder build=factory.newDocumentBuilder();
Document doc=build.parse(new File(" "+File.separator+" "));//需要解析XML文件路径
//得到节点
NodeList nl=doc.getElementByTagName("linkman");
for(int i=0;i<nl.getlength();i++){
    Element e=(Element)nl.item(i);//取出每一个元素
    System.out.println("姓名:"+e.getElementByTagName("name").getFirstChild().getNodeValue());
    System.out.println("邮箱:"+e.getElementByTagName("email").getFirstChild().getNodeValue());
}




------DOM创建XML方法--------------

//取得DocmentBuilderFactory对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//取得DocmentBuilder对象
DocumentBuilder build=factory.newDocumentBuilder();
Document doc=build.newDocment();//创建一个新的XML文件

Element addresslist=doc.createElement("addresslist");
Element linkman=doc.createElement("linkman");
Element name=doc.createElement("name");
Element email=doc.createElement("email");
//设置节点内容
name.appendChild(doc.createTextNode("李三"));
email.appendChild(doc.createTextNode("liagnshan1024@126.com"));
linkman.appendChild(name);
linkman.appendChild(email);
addresslist.appendChild(linkman);
doc.appendChile(addresslist);
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t=tf.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING,"GBK");
DOMSource source=new DOMSource(doc);//准备输出文档
StreamResult result=new StreamResult(new File(" D:"+File.separator+"*.xml"));
t.transform(source,result);




---------SAX解析XML方法--------

分两部完成:
1、首先建立一个SAX解析器如下:

import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class MySAX extends DefaultHandler
{
    public void startDocument()
                    throws SAXException{
        System.out.println("<?xml version=\"1.0\" encoding=\"GBK\">");
        
    }
    public void startElement(String uri,
                        String localName,
                        String qName,
                        Attribute attributes)
                throws SAXException{
        System.out.print("<");
        System.out.print(qName);
        if(attributes!=null){//如果存在了属性
            for(int x=0;x<attributes.getLength();x++){
                System.out.println(" "+attributes.getQName(x)+"=\""+attributes.getValue(x)+"\"");
                
            }
        }
    }
    public void endElement(String uri,
                        String localName,
                        String qName)
                throws SAXException{
        System.out.print("<");
        System.out.print(qName);
        System.out.print(">");
    }
    public void characters(char[] ch,
                        int start,
                        int length)
                throws SAXException{
        System.out.print(new String(ch,start,length));
    }
    public void endDocument()
                throws SAXException{
            System.out.println("文档结束!");
        }
}


2、然后在进行解析如下:
import java.io.*;
import javax.xml.parsers.*;
public class TestSAX{
    public static void main(String args[]){
        //建立SAX解析工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser=factory.newSAXParser();
        parser.parse("d:"+File.separator+"*.xml",new MySAX());
    }
}





---------JDOM生成XML操作------------

public class WriterXML{
    public static void main(String args[]) throws {
        Element addresslist=new Element("addresslist");
        Element linkman=new Element("linkman");
        Element name=new Element("name");
        Element email=new Element("email");
        Attribute id=new Attribute("id","liang");
        Document doc =new Document(addresslist);//定义Document对象
        name.setText("李三");
        name.setAttribute(id);
        email.setText("liagnshan1024@126.com ");
        linkman.addContent(name);
        linkman.addContent(email);
        addresslist.addContent(linkman);
        XMLOutputter out=new XMLOutputter();
        out.setFormat(out.getFormat().setEncoding("GBK"));//设置编码问题--可不加
        out.output(doc,new FileOutputStream(new File("D:"+File.separator+"*.xml"));
    }    
    
}


---------JDOM解析XML操作------------
public class ReaderXML{
    public static void main(String args[]){
        SAXBuilder builder=new SAXBuilder();
        Document read_doc=builder.build(new File("d:"+File.separator+"*.xml"));
        Element root=read_doc.getRootElement();//取得根节点
        List list=root,getChildren("linkman");//取得linkman下所有的节点
        for(int x=0;x<list.size();x++){
            Element e=(Element)list.get(x);
            String name=e.getChildText("name");//得到那么子节点的所有内容
            String id =e.getChild("name").getAttribute("id").getValue();
            String email=e.getChildText("email");
            System.out.println("-----------联系人---------");
            System.out.println("姓名:"+name+",编号:"+id);
            System.out.println("EMAIL:"+email);
            System.out.println("-------------------------");
            System.out.println();
        }
    }    
    
}





---------DOM4J生成XML操作------------
public class DOM4JWriter
{
    public static void main(String args[]){
        Document doc=new DocumentHelper.createDocument();
        Element addresslist=doc.addElement("addresslist");
        Element linkman=addresslist.addElement("linkman");
        Element name=linkman.addElement("name");
        Element email=linkman.addElement("email");
        name.setText("hello");
        email.setText("liagnshan1024@126.com");
        OutputFormat format=OutputFormat.createPrettyPrint();
        format.setEncoding("GBK");
        XMLWriter writer=new XMLWriter(new FileOutputStream(new File("D:"+File.separator+"*.xml",format));
        writer.write(doc);//进行输出
        writer.close();

    }
}



---------DOM4J生成XML操作------------
public class DOM4JReader
{
    public static void main(String args[]){
    File file=new File("D:"+File.separator+"*.xml");
    SAXReader reader=new SAXReader();
    Document doc =reader.read(file);
    Element root=doc.getRootElement();//取得根节点
    //JDOM操作的时候是要取得根节点的
    Iterator iter=root.elementIterator();
    while(iter.hasNext()){
        Element linkman=(Element)iter.next();
        System.out.println("姓名:"+linkman.elementText("name"));
        System.out.println("邮箱:"+linkman.elementText("email"));
    }
    
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值