dom4j 解析xml 获取不到根节点

2025-05-04 16:49:04
推荐回答(1个)
回答1:

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 Xstream { @SuppressWarnings("rawtypes") public static void xmlPrase(String xml){ try {// Document document=DocumentHelper.parseText(xml);//解析字符串 SAXReader reader = new SAXReader(); //解析xml文件 Document document = reader.read(new File("/test/test.xml"));//解析xml文件
Element rootElt = document.getRootElement(); Iterator bodyIter = rootElt.elementIterator(); while(bodyIter.hasNext()){ Element oe = (Element) bodyIter.next(); if(oe.getName().equals("brank")) System.out.println(oe.getStringValue()); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args){ xmlPrase(""); } //xml文件 如下/* a b c d e */}

获取根节点,System.out.println(rootElm.getName()),不是getTest()