以下面这个简单的XML文件为基础,给出一段能读取,修改该XML的java代码
最好是调试通过的…… 我是小白,自己不会整的;
具体实现功能:
1 新增加1个节点
<book id="B04">
<name>book4</name>
<price>40</price>
<memo>This is book4</memo>
</book>
2 修改节点1 <book id="B01">
<name>book1</name>
<price>100</price>
<memo>This is book1</memo>
</book>
3删除节点2
<book id="B02">
<name>book2</name>
<price>20</price>
<memo>This is book2</memo>
</book>
4最好是符合W3C规范的?
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="B01">
<name>book1</name>
<price>10</price>
<memo>This is book1</memo>
</book>
<book id="B02">
<name>book2</name>
<price>20</price>
<memo>This is book2</memo>
</book>
<book id="B03">
<name>book3</name>
<price>30</price>
<memo>This is book3</memo>
</book>
</books>
最好是调试通过的…… 我是小白,自己不会整的;
具体实现功能:
1 新增加1个节点
<book id="B04">
<name>book4</name>
<price>40</price>
<memo>This is book4</memo>
</book>
2 修改节点1 <book id="B01">
<name>book1</name>
<price>100</price>
<memo>This is book1</memo>
</book>
3删除节点2
<book id="B02">
<name>book2</name>
<price>20</price>
<memo>This is book2</memo>
</book>
4最好是符合W3C规范的?
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="B01">
<name>book1</name>
<price>10</price>
<memo>This is book1</memo>
</book>
<book id="B02">
<name>book2</name>
<price>20</price>
<memo>This is book2</memo>
</book>
<book id="B03">
<name>book3</name>
<price>30</price>
<memo>This is book3</memo>
</book>
</books>
package my.test;import java.io.IOException;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 uDom { Document doc=null;
public uDom(String xmlfile) {
DocumentBuilder dbf;
try {
dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = dbf.parse(xmlfile);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取XML文件节点内容
* @param nodeName 节点名称
* @return
*/
public Object[] readNode(String nodeName) {
Object nodeValue[]=null;
NodeList nodelist = doc.getElementsByTagName(nodeName);
nodeValue=new Object[nodelist.getLength()];
//System.out.println("getLength:" + nodelist.getLength());
//System.out.println("getNodeName"+"\t"+"getNodeValue"+"\t"+"getAttribute");
for (int i = 0; i < nodelist.getLength(); i++) {
Element element =(Element)nodelist.item(i);
//System.out.println(element.getNodeName()+"\t"+element.getNodeValue()+"\t"+element.getAttribute("num"));
nodeValue[i]=element.getNodeValue();
}
return nodeValue;
}
/**
* 读取XML文件节点属性内容
* @param nodeName 节点名称
* @param Attribute 节点属性名称
* @return
*/
public Object[] readNode(String nodeName,String Attribute) {
Object AttrValue[]=null;
NodeList nodelist = doc.getElementsByTagName(nodeName);
AttrValue=new Object[nodelist.getLength()];
for (int i = 0; i < nodelist.getLength(); i++) {
Element element =(Element)nodelist.item(i);
//System.out.println(element.getNodeName()+"\t"+element.getNodeValue()+"\t"+element.getAttribute("num"));
AttrValue[i]=element.getAttribute(Attribute);
}
return AttrValue;
}
public uDom() {
// TODO Auto-generated constructor stub
try {
this.readxml();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public void readxml() throws ParserConfigurationException, SAXException,
IOException {
String nodename = null; short nodetype = 0; String nodevalue = null;
DocumentBuilder dbf = DocumentBuilderFactory.newInstance().newDocumentBuilder();
System.out.println("Get DocumentBuilder Successful..."); Document doc = dbf.parse("d:/TestFile/links.xml");
System.out.println("Get Document Successful..."); NodeList nl1 = doc.getElementsByTagName("message");
System.out.println("Get NodeList(links) Successful...");
System.out.println("getLength:" + nl1.getLength()); Node node2 = doc.getFirstChild().getChildNodes().item(1);
// Node node3 = doc.getFirstChild();
Node node1 = nl1.item(4);
// Node node2 = doc.getFirstChild(); // Node node3 = node2.getFirstChild();
// Node node4 = node3.getFirstChild();
for (int i = 0; i < 2; i++) {
System.out.println(node2.getChildNodes().item(i).getNodeName());
System.out.println(node2.getChildNodes().item(i).getNodeValue());
} // System.out.println(node2.getFirstChild().getNextSibling().getNodeName());
System.exit(0); nodename = node1.getFirstChild().getNodeName(); nodetype = node1.getFirstChild().getNodeType(); nodevalue = node1.getFirstChild().getNodeValue(); System.out.println("getNodeName:" + nodename);
System.out.println("getNodeType:" + nodetype);
System.out.println("getNodeValue:" + nodevalue);
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
uDom udom = new uDom("xml/test.XML");
System.out.println("读取XML文件成功~~");
Object[] temp=udom.readNode("root","num");
System.out.println("获得节点长度为:"+temp.length);
for(int i=0;i<temp.length;i++) {
//temp[i]可能会得到空指针异常
System.out.println(i+" Value: "+temp[i].toString());
}
}}
1、sax (常用,生成xml功能比较弱) sax Jar下载(1770k)
基于解析事件的拦截
2、jdom (常用)jdom Jar下载(1770k) 还需要sax包
解析详细的元素时基于树(针对整个xml文件解析时,是基于对象的)
3、dom4j (常用)dom4j Jar下载(475k)
解析详细的元素时基于树(针对整个xml文件解析时,是基于对象的)
4、dom(基础)dom Jar包下载(201k)
解析详细的元素时基于树(针对整个xml文件解析时,是基于对象的)
我个人认为Dom4j比较简单!如果你是一个新手,建议你发一下E_mail 给你传一份完整的项目。
String name;
String price;
String meme;
String book_id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getMeme() {
return meme;
}
public void setMeme(String meme) {
this.meme = meme;
}
public String getBook_id() {
return book_id;
}
public void setBook_id(String book_id) {
this.book_id = book_id;
}
}
1.添加节点
public void addNode() {
SAXReader reader = new SAXReader();
try {
Document doc = reader.read(new File("dom4j.xml"));
Element root = doc.getRootElement();
Element bookElement = root.addElement("book");
bookElement.addAttribute("id", "B04");
Element nameElement = bookElement.addElement("name");
nameElement.setText("book4");
Element priceElement = bookElement.addElement("price");
priceElement.setText("40");
Element memoElement = bookElement.addElement("memo");
memoElement.setText("This is book4");
XMLWriter writer = new XMLWriter(new FileWriter("dom4j.xml"));
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2.修改节点
public void refNode() {
SAXReader reader = new SAXReader();
try {
Document doc = reader.read(new File("dom4j.xml"));
Element root = doc.getRootElement();
List ls = root.elements();
Element el = (Element) ls.get(0);
Element price = el.element("price");
price.setText("100");
XMLWriter writer = new XMLWriter(new FileWriter("dom4j.xml"));
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3.删除节点
public void delNode() {
SAXReader reader = new SAXReader();
try {
Document doc = reader.read(new File("dom4j.xml"));
Element root = doc.getRootElement();
List ls = root.elements();
Element el = (Element) ls.get(1);
root.remove(el);
XMLWriter writer = new XMLWriter(new FileWriter("dom4j.xml"));
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我的油箱是[email protected] 快来给我加油~~ ^_^
TO legend_jhz
试了你的方法,但是出错了~
Document doc = reader.read(new File("dom4j.xml"));
错误如下:
org.dom4j.DocumentException: Error on line 2 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:355)
at org.dom4j.io.SAXReader.read(SAXReader.java:219)
at page1.TEST.addNode(TEST.java:24)
at page1.TEST.main(TEST.java:17)
Nested exception:
org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:215)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:386)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:316)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1438)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPIData(XMLScanner.java:689)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanPIData(XMLDocumentFragmentScannerImpl.java:750)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPI(XMLScanner.java:664)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(XMLDocumentScannerImpl.java:845)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
at org.dom4j.io.SAXReader.read(SAXReader.java:339)
at org.dom4j.io.SAXReader.read(SAXReader.java:219)
at page1.TEST.addNode(TEST.java:24)
at page1.TEST.main(TEST.java:17)
Nested exception: org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:215)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:386)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:316)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1438)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPIData(XMLScanner.java:689)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanPIData(XMLDocumentFragmentScannerImpl.java:750)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPI(XMLScanner.java:664)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(XMLDocumentScannerImpl.java:845)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
at org.dom4j.io.SAXReader.read(SAXReader.java:339)
at org.dom4j.io.SAXReader.read(SAXReader.java:219)
at page1.TEST.addNode(TEST.java:24)
at page1.TEST.main(TEST.java:17)