xml源文件:
<?xml version="1.0" encoding="utf-8"?>
<contactList>
<contact id="001" name="aa1" ss="22">
<name>張三</name>
<age>20</age>
<phone>134222223333</phone>
<email>[email protected]</email>
<qq>432221111</qq>
</contact>
<contact id="003">
<name>lisi</name>
<age>20</age>
<phone>134222225555</phone>
<email>[email protected]</email>
<qq>432222222</qq>
</contact>
</contactList>
讀取xml文檔,返回Document
SAXReader read = new SAXReader();
Document doc = read.read(new File("./src/contact.xml"));//返回Document對象
1.獲取節點
a.)將獲取的節點便利輸出:
Iterator<Node> inter = doc.nodeIterator();//獲取節點
while(inter.hasNext()){//判斷是否有下一個元素
Node node=inter.next();
String name = node.getName();
System.out.println(name);//打印出節點名稱
}
b.)獲取該標籤節點下的子節點:
if(node instanceof Element){//判斷是否有子節點
Element ele = (Element)node;
Iterator <Node> ite = ele.nodeIterator();
while(ite.hasNext()){
Node nod=ite.next();//打印出子節點名稱
System.out.println(nod.getName());
}
}
#####c.)獲取所有節點:
Element ele = dor.getRootElement();//獲取根節點
getChildNode(ele);//調用方法
//獲取所有子節點的方法並打印
private void getChildNode(Element elem){
System.out.println(elem.getName());//輸出節點
Iterator <Node> it= elem.nodeIterator();
while(it.hasNext()){
Node node = it.next();
if(node instanceof Element){
Element el = (Element)node;
getChildNode(el);//遞歸
}
}
}
2.獲取標籤
a.)先得到根標籤:
Element rootele =doc.getRootElement();//得到根標籤
String name = rootele.getName();
System.out.println(name);
b.)得到當前標籤下的指定名稱的子標籤:
Element contele= rootele.element("contact");//得到當前標籤下的指定名稱的子標籤
System.out.println(contele.getName());
c.)獲得當前標籤下指定名稱的所有子標籤:
Iterator<Element> it=rootele.elementIterator("contact");//獲得當前標籤下指定名稱的所有子標籤
while(it.hasNext()){
Element elem = it.next();
System.out.println(elem.getName());
}
3.獲取屬性
a.)先獲得屬性所在的標籤對象:
//獲得屬性,先獲得屬性所在的標籤對象,然後獲取屬性
Element contele =doc.getRootElement().element("contact");
b.)得到指定名稱屬性值
方法一:
//得到屬性
//得到指定名稱屬性值
String IDValue= contele.attributeValue("id");
System.out.println(IDValue);
方法二:
//得到指定屬性名稱的屬性對象和屬性值
Attribute attr = contele.attribute("id");
System.out.println(attr.getName()+"="+attr.getValue());
c.)得到指定名稱的所有屬性值
方法一:
//獲取當前標籤所有的屬性對象和屬性值
List<Attribute> list= contele.attributes();
for(Attribute arr:list){
System.out.println(arr.getName()+"="+arr.getValue());
}
方法二:
//獲取當前標籤所有的屬性對象和屬性值
Iterator<Attribute> it= contele.attributeIterator();
while(it.hasNext()){
Attribute aa= it.next();
System.out.println(aa.getName()+"="+aa.getValue());
}
4.獲取文本
a.)先獲取文本標籤:
//獲取文本(先獲取文本標點,在獲取文本內容)
Element neamEle = doc.getRootElement().element("contact").element("name");
b.)獲取文本內容:
//得到文本內容
String nameText = neamEle.getText();
System.out.println(nameText);
c.)得到指定標籤名的文本內容:
//得到指定標籤名的文本內容
String text2= doc.getRootElement().element("contact").elementText("name");
System.out.println(text2);