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 javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.DocumentBuilder
import org.w3c.dom.Document
import org.w3c.dom.NodeList
import org.w3c.dom.Node
import org.w3c.dom.Element
import java.io.File
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Users/mkyong/staff.xml")
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance()
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder()
Document doc = dBuilder.parse(fXmlFile)
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize()
System.out.println("Root element :" + doc.getDocumentElement().getNodeName())
NodeList nList = doc.getElementsByTagName("staff")
System.out.println("----------------------------")
for (int temp = 0temp <nList.getLength()temp++) {
Node nNode = nList.item(temp)
System.out.println("\nCurrent Element :" + nNode.getNodeName())
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode
System.out.println("Staff id : " + eElement.getAttribute("id"))
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent())
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent())
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent())
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent())
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)