日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

JAVA中利用DOM解析XML文档

發布時間:2024/1/17 asp.net 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA中利用DOM解析XML文档 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JAVA中利用DOM解析XML文檔 package org.sws.utils;

import java.io.File;
import java.io.IOException;

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

import org.sws.model.Server;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigurationUtil {
private String conf = "configuration.xml";
//Document是XML在內存中的一個鏡像,獲取了Document就可以通過對內存的操作來實現對XML的操作。
private Document doc = null ;

public Server getConfig(){
//從DocumentBuilderFactory中獲取一個DocumentBuilder的實例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
//使用DocumentBuilder來產生一個Document實例
doc = db.parse(new File(conf));

//Element代表XML中的一個標簽對,可用于獲取屬性值
Element element = doc.getDocumentElement();
//獲取該Element的標簽名
System.out.println("Root Element : "+element.getTagName());
//通過標簽名來獲取多個節點
NodeList nodeList = doc.getElementsByTagName("Service");
System.out.println("NodeList Length : "+nodeList.getLength());

Node node = nodeList.item(0);
System.out.println("First Node : "+node.getNodeName());
//通過Agetttributes()方法來獲取一個NamedNodeMap實例,該實例包含標簽屬性值
NamedNodeMap attrs = node.getAttributes();

for (int i=0; i<attrs.getLength(); i++){
Node attr = attrs.item(i);
System.out.println(attr.getNodeName()+" : "+attr.getNodeValue());
}

NodeList childNodes = node.getChildNodes();

for (int i=0; i<childNodes.getLength(); i++){
Node child = childNodes.item(i);
//當子節點是一個Element時才能獲取該元素的標簽名和屬性值
if (child instanceof Element)
{
System.out.println(child.getNodeName()
+" : "+child.getFirstChild().getNodeValue());
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null ;
}

}

XML文件:

<?xml version='1.0' encoding='utf-8'?>
<Server>
<Service name="SampleWebServer">
<Listen>8080</Listen>
<Protocol>HTTP/1.1</Protocol>
<Host>localhost</Host>
<Root>/html</Root>
</Service>

<Service name="SampleWebServer1">
<Listen>8081</Listen>
<Protocol>HTTP/1.1</Protocol>
<Host>localhost</Host>
<Root>/html</Root>
</Service>
</Server>



posted on 2012-01-25 14:19 Jesuca 閱讀(...) 評論(...) 編輯 收藏

轉載于:https://www.cnblogs.com/Jesuca/archive/2012/01/25/2329368.html

總結

以上是生活随笔為你收集整理的JAVA中利用DOM解析XML文档的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。