62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class DomTest {
public DomTest() {
};
/**
* 递归遍历方法
*
* @param element
*/
public void getElementList(Element element) {
List elements = element.elements();
if (elements.size() == 0) {
// 没有子元素
String xpath = element.getPath();
String value = element.getTextTrim();
System.out.println("xpath:" + xpath);
System.out.println("value:" + value);
} else {
// 有子元素
for (Iterator it = elements.iterator(); it.hasNext();) {
Element elem = (Element) it.next();
// 递归遍历
getElementList(elem);
}
}
}
public void readElement(String xpath, String fileName) {
SAXReader saxReader = new SAXReader();
try {
Document xmlDoc = saxReader.read(new File(fileName));
List list1 = xmlDoc.selectNodes(xpath);
for (Iterator i = list1.iterator(); i.hasNext();) {
Attribute attribute = (Attribute) i.next();
if (attribute.getValue().equalsIgnoreCase("hh")) {
getElementList(attribute.getParent());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
DomTest domTest = new DomTest();
domTest.readElement("//a/b/@name", "dom4jTest.xml");
}
}
/**
* <root>
* <!--利用dom4j创建document-->
* <book type="org.active.book">创建Document</book>
* </root>
* @desc:
* @throws Exception
*/
private void parse() throws Exception {
// JDK1.6自带的解析方式
javax.xml.parsers.DocumentBuilderFactory documentFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder builder = documentFactory.newDocumentBuilder();
org.w3c.dom.Document document = builder.parse(DomDocument.class.getResourceAsStream("/dom.xml"));
Node root = document.getFirstChild();
System.out.println("@JDK1.6 root name:"+root.getNodeName());
NodeList childs = root.getChildNodes();
for(int i=0;i<childs.getLength();i++){
Node node = childs.item(i);
if("book".equals(node.getNodeName())){
//取到节点时,取属性
NamedNodeMap map = node.getAttributes();
System.out.println("@JDK1.6 book node att:"+map.getNamedItem("type"));
}
}
}
/**
* @desc:利用String 字符串来生生成document
* @return
* @throws DocumentException
*/
private void createDocument(String str) throws Exception{
Document document =DocumentHelper.parseText(str);
Element root = document.getRootElement();
System.out.println("root name :"+root.getName());
System.out.println("root xml string :"+root.asXML());
Element child = root.element("book");
System.out.println("book xml String:"+child.asXML());
System.out.println("book's type: "+child.attributeValue("type"));
}