import java.util.List
import org.dom4j.Document
import org.dom4j.DocumentException
import org.dom4j.Element
import org.dom4j.io.SAXReader
public class XMLPaser {
public static void main(String[] args) {
paserXML()
}
public static void paserXML(){
SAXReader reader = new SAXReader()
try {
// 读取XML文件
Document doc = reader.read("NewFile.xml")
Element root = doc.getRootElement()
System.out.println(root.getName())
List<Element> param = root.elements()
for (Element element : param) {
if(element.attributeValue("name").equals("a")){
System.out.println(element.getText())
}
}
} catch (DocumentException e) {
e.printStackTrace()
}
}
}
import java.util.Listimport org.dom4j.Document
import org.dom4j.DocumentException
import org.dom4j.Element
import org.dom4j.io.SAXReader
public class XmlTester {
public static void main(String[] args) throws DocumentException {
// 使用了dom4j解析xml
// 读取目录下用来测试的test.xml文件,取得xml主内容
Document document = new SAXReader().read("src/abc/test.xml").getDocument()
int i = 1
// 遍历文档根节点(wuxialist)下的子节点列表,即txtbook节点的集合
for(Element txtbook : (List<Element>)document.getRootElement().elements()){
//取得txtbook节点下的name节点的内容
System.out.println(i+"."+txtbook.element("name").getText())
i++//原来这里少些了这一行,先补上
}
}
}
import w c dom *
import javax xml parsers *
import java io *
public class Parse{
//Document可以看作是XML在内存中的一个镜像 那么一旦获取这个Document 就意味着可以通过对
//内存的操作来实现对XML的操作 首先第一步获取XML相关的Document
private Document doc=null
public void init(String xmlFile) throws Exception{
//很明显该类是一个单例 先获取产生DocumentBuilder工厂
//的工厂 在通过这个工厂产生一个DocumentBuilder
//DocumentBuilder就是用来产生Document的
DocumentBuilderFactory dbf=DocumentBuilderFactory newInstance()
DocumentBuilder db=dbf newDocumentBuilder()
//这个Document就是一个XML文件在内存中的镜像
doc=db parse(new File(xmlFile))
}
//该方法负责把XML文件的内容显示出来
public void viewXML(String xmlFile) throws Exception{
this init(xmlFile)
//在xml文件里 只有一个根元素 先把根元素拿出来看看
Element element=doc getDocumentElement()
System out println( 根元素为: +element getTagName())
NodeList nodeList=doc getElementsByTagName( dbstore )
System out println( dbstore节点链的长度: +nodeList getLength())
Node fatherNode=em( )
System out println( 父节点为: +fatherNode getNodeName())
//把父节点的属性拿出来
NamedNodeMap attributes=fatherNode getAttributes()
for(int i= i<attributes getLength()i++){
Node attribute=em(i)
System out println( dbstore的属性名为: +attribute getNodeName()+ 相对应的属性值为: +attribute getNodeValue())
}
NodeList childNodes = fatherNode getChildNodes()
System out println(childNodes getLength())
for(int j= j<childNodes getLength()j++){
Node childNode=em(j)
//如果这个节点属于Element 再进行取值
if(childNode instanceof Element){
//System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue())
System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue())
}
}
}
public static void main(String[] args)throws Exception{
Parse parse=new Parse()
//我的XML文件
parse viewXML( netct xml )
}
lishixinzhi/Article/program/Java/hx/201311/26710