下个dom4j包我下面的方法笨了点不知道还有好的不
import javaioFile;
import javautilIterator;
import orgdom4j;
import orgdom4jioSAXReader;
public class ResultXmlTest1 {
public static void main(String args[])
{
SAXReader reader=new SAXReader();
try
{
Document doc=readerread(new File("resultxml"));
Element root=docgetRootElement();
for(Iterator ite=rootelementIterator();itehasNext();)
{
Element ele=(Element)itenext();
for(Iterator iter=eleelementIterator();iterhasNext();)
{
Element elem=(Element)iternext();
//Systemoutprintln(elemgetName());
for(Iterator itera=elemelementIterator();iterahasNext();)
{
Element eleme=(Element)iteranext();
//Systemoutprintln(elemegetName());
for(Iterator iterat=elemeelementIterator();iterathasNext();)
{
Element elemem=(Element)iteratnext();
//Systemoutprintln(elememgetName());
for(Iterator iterato=elememelementIterator();iteratohasNext();)
{
Element elememe=(Element)iteratonext();
//Systemoutprintln(elememegetName());
for(Iterator last=elememeelementIterator();lasthasNext();)
{
Element elemLast=(Element)lastnext();
//Systemoutprintln(elemLastgetName());
for(Iterator at=elemLastattributeIterator();athasNext();)
{
Attribute att=(Attribute)atnext();
if(attgetName()equals("start"))
Systemoutprintln(attgetText());
}
}
}
}
}
}
}
}catch(DocumentException e)
{
eprintStackTrace();
}
}
}
dom4j中,使用Elementattributes方法可以获取到节点的属性,而使用elements则可以获取相应的子节点
比如:
Element root = docgetRootElement();
List attrList = rootattributes();
for (int i = 0; i < attrListsize(); i++) {
//属性的取得
Attribute item = (Attribute)attrListget(i);
Systemoutprintln(itemgetName() + "=" + itemgetValue());
}
List childList = rootelements();
for (int i = 0; i < childListsize(); i++) {
//子节点的 *** 作
Element it = (Element) childListget(i);
//对子节点进行其它 *** 作
}
import javaioFile;
import javautilList;
import orgdom4jDocument;
import orgdom4jDocumentException;
import orgdom4jNode;
import orgdom4jioSAXReader;
public class XmlTest2 {
public static void main(String[] args) {
SAXReader reader = new SAXReader();
readersetEncoding("UTF-8");
Document doc = null;
try {
File file = new File("test2xml");
doc = readerread(file);
printNode(docselectNodes("DSExport/Job"));
}
catch (DocumentException e) {
eprintStackTrace();
}
}
public static void printNode(List<Node> nodeList) {
for (Node jobNode : nodeList) {
printProperty(jobNodeselectNodes("Record/Property"));
printProperty(jobNodeselectNodes("Record/Collection/SubRecord/Property"));
}
}
public static void printProperty(List<Node> propertyNodeList) {
for (Node propertyNode : propertyNodeList) {
Systemoutprintln(propertyNodegetUniquePath() + ">>" + propertyNodeselectSingleNode("@Name")getText() + ":" + propertyNodegetText());
}
}
}
能 但是比较麻烦 返回的是list 你还得遍历;你要是想取 node name="a" 的这个节点,可以用getQName(String qualifiedName),具体的你可以参考dom4j文档
以上就是关于如何用java取得XML节点的属性值全部的内容,包括:如何用java取得XML节点的属性值、Dom4j怎么获取xml文件中某元素所在的行号、dom4j解析xml重复节点等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)