1.DOM解析xml
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.NodeList;
import org.xml.sax.SAXException;
public class XMLTest {
public static void main(String[] args) {
String fileName = "C:\\fy.xml";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
Document document = null;
try {
db = factory.newDocumentBuilder();
document = db.parse(fileName);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Element element=document.getDocumentElement();
NodeList list=element.getElementsByTagName("fy");
for(int i=0;i<list.getLength();i++){
Element report=(Element)list.item(i);//
String name=report.getAttribute("name").trim();
String age=report.getAttribute("age");
String address=report.getAttribute("address");
System.out.println(name+"--"+age+"--"+address);
}
}
}
xml文件:
<?xml version="1.0" encoding="GB2312" ?> <yyming> <fy name="小牛犊" age="23" address="成都" /> <fy name="富姐" age="21" address="重庆" /> </yyming>
运行结果:
小牛犊--23--成都
富姐--21--重庆
2.DOM4J解析xml
import java.io.File;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class DOM4JTest {
public static void main(String[] args) {
File f=new File("c:\\fy.xml");
SAXReader reader=new SAXReader();
try {
Document dom=reader.read(f);
Element root=dom.getRootElement();
Element foo;
Element child;
for(Iterator i=root.elementIterator("fy");i.hasNext();){
foo=(Element)i.next();
System.out.println("-name--"+foo.attributeValue("name"));
System.out.println("-age--"+foo.attributeValue("age"));
System.out.println("-address--"+foo.attributeValue("address"));
for(Iterator j=foo.elementIterator("flh");j.hasNext();){
child=(Element)j.next();
System.out.println("---child---"+child.attributeValue("book"));
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
xml文件:
<?xml version="1.0" encoding="GB2312" ?> <yyming> <fy name="小牛犊" age="23" address="成都" > <flh book="java"/> <flh book="struts"/> </fy> <fy name="富姐" age="21" address="重庆" /> </yyming>
运行结果:
-name--小牛犊
-age--23
-address--成都
---child---java
---child---struts
-name--富姐
-age--21
-address--重庆