XML读写有很多的方法~~
JAVA中有丰富的类对XML文件进行操作~~比如XMLReader....JDOM...DOM等等~~
以下是我从网上资料找到,并进行试验成功的例子~~
采用的是DOM~~~并不需要下载其他的包~~
代码
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class ReadXML{
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException{
String customerID=null;
String customerName=null;
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder=domfac.newDocumentBuilder();//需要SAXException异常
InputStream is=new FileInputStream("d:\\test.xml");
Document doc=dombuilder.parse(is);
Element root=doc.getDocumentElement();//获取根节点
NodeList customer=root.getChildNodes();//获取子节点,是个集合
for(int i=0;i<customer.getLength();i++){
Node info=customer.item(i);
for(Node node=info.getFirstChild();node!=null;node=node.getNextSibling()){
if(node.getNodeType()==Node.ELEMENT_NODE){
if(node.getNodeName().equals("customerID")){
customerID=node.getFirstChild().getNodeValue();
}
if(node.getNodeName().equals("customerName")){
customerName=node.getFirstChild().getNodeValue();
}
}
}
}
System.out.println(customerID);
System.out.println(customerName);
}
}
这是读XML的过程~~~下面是写XML的过程
代码
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class JavaXML {
public static void main(String[] args) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();//文件工厂初始化
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.newDocument();//创建一个Document实例
Element customers=doc.createElement("customers");
Element customer=doc.createElement("customer");
Element customerID=doc.createElement("customerID");
Element customerName=doc.createElement("customerName");
customerID.appendChild(doc.createTextNode("123"));
customerName.appendChild(doc.createTextNode("zjj"));
customer.appendChild(customerID);
customer.appendChild(customerName);
customers.appendChild(customer);
doc.appendChild(customers);//将子节点添加到根节点,实际上doc是这个XML的根节点
TransformerFactory tff=TransformerFactory.newInstance();//解析器初始化
Transformer tformer=tff.newTransformer();
tformer.transform(new DOMSource(doc), new StreamResult("d:\\test.xml"));
}
}
这是我个人的经验~~~
很好用~~对XML的读写很方便~~~
大家可以去尝试下~~