java解析xml格式请求报文

import java.io.File;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Document;
public class readdemo {
public static void main(String []args) throws Exception{
readdemo demo=new readdemo();
demo.testGetRoot();
}
public void testGetRoot() throws Exception{
SAXReader sax=new SAXReader();//创建一个SAXReader对象
File xmlFile=new File(“C:\Users\20433\Desktop\sxfdemo.xml”);//根据指定的路径创建file对象
org.dom4j.Document document=sax.read(xmlFile);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root=document.getRootElement();//获取根节点
this.getNodes(root);//从根节点开始遍历所有节点
}
public void getNodes(Element node){
System.out.println("--------------------");
//当前节点的名称、文本内容和属性
System.out.println(“当前节点名称:”+node.getName());//当前节点名称
System.out.println(“当前节点的内容:”+node.getTextTrim());//当前节点名称
List listAttr=node.attributes();//当前节点的所有属性的list
for(Attribute attr:listAttr){//遍历当前节点的所有属性
String name=attr.getName();//属性名称
String value=attr.getValue();//属性的值
System.out.println(“属性名称:”+name+“属性值:”+value);
}
//递归遍历当前节点所有的子节点
List listElement=node.elements();//所有一级子节点的list
for(Element e:listElement){//遍历所有一级子节点
this.getNodes(e);//递归
}
}
}

猜你喜欢

转载自blog.csdn.net/weixin_37565521/article/details/84827190
今日推荐