① java解析xml得到節點的值
importjava.io.File;
importjava.util.Iterator;
importorg.dom4j.Document;
importorg.dom4j.DocumentException;
importorg.dom4j.Element;
importorg.dom4j.io.SAXReader;
publicclassParseXml{
publicstaticvoidmain(String[]args)throwsDocumentException{
SAXReaderreader=newSAXReader();
Documentdoc=reader.read(newFile("d:/test.xml"));
Elementroot=doc.getRootElement();
Elementrecord=root.element("Record");
Iterator<Element>it=record.elementIterator("Field");
while(it.hasNext()){
Elementelement=it.next();
Elementname=element.element("Name");
System.out.println(name.getText());
Elementvalue=element.element("Value");
ParseXml.parseValue(value);
}
}
publicstaticvoidparseValue(Elementvalue){
Iterator<Element>it=value.elementIterator();
if(it.hasNext()){
while(it.hasNext()){
Elementelement=it.next();
ElementinnerField=element.element("Field");
ElementinnerName=innerField.element("Name");
System.out.println(innerName.getText());
ElementinnerValue=innerField.element("Value");
parseValue(innerValue);
}
}else{
System.out.println(value.getText());
}
}
}
② java如何讀取xml節點元素值
java讀取xml節點元素,主要使用java提供的解析xml的工具類SAXParserFactory,如下代碼:
packagexml.xmlreader;
importjava.io.File;
importjava.net.URL;
importjava.util.Properties;
importjavax.xml.parsers.SAXParser;
importjavax.xml.parsers.SAXParserFactory;
publicclassCFGParser{//解析xml文件的工具類
privatePropertiesprops;
publicPropertiesgetProps(){
returnprops;
}
publicvoidsetProps(Propertiesprops){
this.props=props;
}
publicvoidparse(Stringfilename)throwsException
{
CFGHandlerhandler=newCFGHandler();
SAXParserFactoryfactory=SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParserparser=factory.newSAXParser();
URLconfURL=super.getClass().getClassLoader().getResource(filename);
if(confURL==null){
System.out.println("Can'tfindconfigrationfile.");
return;
}
try
{
parser.parse(confURL.toString(),handler);
this.props=handler.getProps();
}
finally{
factory=null;
parser=null;
handler=null;
}
}
publicvoidparseFile(Stringfilename)
throwsException
{
CFGHandlerhandler=newCFGHandler();
SAXParserFactoryfactory=SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
SAXParserparser=factory.newSAXParser();
Filef=newFile(filename);
if((f==null)||(!f.exists()))
return;
try
{
parser.parse(f,handler);
this.props=handler.getProps();
}
finally{
factory=null;
parser=null;
handler=null;
}
}
}
packagexml.xmlreader;
importjava.util.Properties;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
{
privatePropertiesprops;
privateStringcurrentSet;
privateStringcurrentName;
=newStringBuffer();
publicCFGHandler()
{
this.props=newProperties();
}
publicPropertiesgetProps(){
returnthis.props;
}
publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)
throwsSAXException
{
this.currentValue.delete(0,this.currentValue.length());
this.currentName=qName;
}
publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException
{
this.currentValue.append(ch,start,length);
}
publicvoidendElement(Stringuri,StringlocalName,StringqName)
throwsSAXException
{
this.props.put(qName.toLowerCase(),this.currentValue.toString().trim());
}
}
xml文件
<?xmlversion="1.0"encoding="UTF-8"?>
<xml-body>
<refresh_userlistdesc="用戶列表刷新間隔時間(秒)">6</refresh_userlist>
<refresh_messagedesc="短消息刷新間隔時間(秒)">10</refresh_message>
<morningbegindesc="上午上班時間">23:00</morningbegin>
<morningenddesc="上午下班時間">12:00</morningend>
<afternoonbegindesc="下午上班時間">18:00</afternoonbegin>
</xml-body>
jsp獲取各個節點的值:
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<html>
<jsp:useBeanid="cfgp"scope="page"class="xml.xmlreader.CFGParser"></jsp:useBean>
<body>
<%
cfgp.parse("kaoqin.xml");
Propertiespro=cfgp.getProps();
StringstTime=pro.getProperty("morningbegin");
StringedTime=pro.getProperty("morningend");
Stringafternoonbegin=pro.getProperty("afternoonbegin");
out.println(stTime+" "+edTime+" "+afternoonbegin);
System.out.println(stTime+" "+edTime+" "+afternoonbegin);
%>
</body>
</html>
③ java判斷xml節點元素屬性是否存在,解析方式為DOM4j,請教各位大神,謝謝!急....
記得貌似如果值不存在會返回一個null吧,直接判斷值是否為null即可
④ java解析xml有幾種方法
DOM(Document Object Model)解析
優點
允許應用程序對數據和結構做出更改
訪問是雙向的,可以在任何時候在樹中上、下導航獲取、操作任意部分的數據
缺點
解析XML文檔的需要載入整個文檔來構造層次結構,消耗內存資源大。
應用范圍
遍歷能力強,常應用於XML文檔需要頻繁改變的服務中。
解析步驟
創建一個 DocumentBuilderFactory 對象
創建一個 DocumentBuilder 對象
通過 DocumentBuilder 的 parse() 方法載入 XML 到當前工程目錄下
通過 getElementsByTagName() 方法獲取所有 XML 所有節點的集合
遍歷所有節點
通過 item() 方法獲取某個節點的屬性
通過 getNodeName() 和 getNodeValue() 方法獲取屬性名和屬性值
通過 getChildNodes() 方法獲取子節點,並遍歷所有子節點
通過 getNodeName() 和 getTextContent() 方法獲取子節點名稱和子節點值
package Paint;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest {
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse("./src/Paint/hello.xml");
NodeList bookList = document.getElementsByTagName("book"); //節點集
int bookCnt = bookList.getLength();
System.err.println("一共獲取到" + bookCnt +"本書");
for(int i=0; i Node book = bookList.item(i);
NamedNodeMap attrs = book.getAttributes();
for(int j=0; j Node attr = attrs.item(j);
System.err.println(attr.getNodeName()+"---"+attr.getNodeValue());//id
}
NodeList childNodes = book.getChildNodes();
for(int k=0; k if(childNodes.item(k).getNodeType() == Node.ELEMENT_NODE){
System.out.println(childNodes.item(k).getNodeName()+"---" + childNodes.item(k).getTextContent());
}
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SAX(Simple API for XML)解析
優點
不需要等待所有的數據被處理,解析就可以開始
只在讀取數據時檢查數據,不需要保存在內存中
可以在某一個條件滿足時停止解析,不必要解析整個文檔
效率和性能較高,能解析大於系統內存的文檔
缺點
解析邏輯復雜,需要應用層自己負責邏輯處理,文檔越復雜程序越復雜
單向導航,無法定位文檔層次,很難同時同時訪問同一文檔的不同部分數據,不支持 XPath
解析步驟
獲取一個 SAXParserFactory 的實例
通過 factory() 獲取 SAXParser 實例
創建一個 handler() 對象
通過 parser 的 parse() 方法來解析 XML
SAXTest.java
package Paint;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class SAXTest {
public static void main(String[] args) {
// 獲取實例
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
SAXParserHandler handler = new SAXParserHandler();
parser.parse("./src/Paint/hello.xml", handler);
System.err.println("共有"+ handler.getBookList().size()+ "本書");
for(Book book : handler.getBookList()){
System.out.println(book.getName());
System.out.println("id=" + book.getId());
System.out.println(book.getAuthor());
System.out.println(book.getYear());
System.out.println(book.getPrice());
System.out.println(book.getLanguage());
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SAXParserHandler.java
package Paint;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserHandler extends DefaultHandler {
String value = null;
Book book = null;
private ArrayList bookList = new ArrayList();
public ArrayList getBookList() {
return bookList;
}
/*
* XML 解析開始
*/
public void startDocument() throws SAXException {
super.startDocument();
System.out.println("xml 解析開始");
}
/*
* XML 解析結束
*/
public void endDocument() throws SAXException {
super.endDocument();
System.out.println("xml 解析結束");
}
/*
* 解析 XML 元素開始
*/
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(qName.equals("book")){
book = new Book();
for(int i=0; i System.out.println(attributes.getQName(i)+"---"+attributes.getValue(i));
if(attributes.getQName(i).equals("id")){
book.setId(attributes.getValue(i));
}
}
}else if(!qName.equals("bookstore")){
System.out.print("節點名:"+ qName + "---");
}
}
/*
*解析 XML 元素結束
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(qName.equals("book")){
bookList.add(book);
book = null;
}
else if(qName.equals("name")){
book.setName(value);
}else if(qName.equals("year")){
book.setYear(value);
}else if(qName.equals("author")){
book.setAuthor(value);
}else if(qName.equals("price")){
book.setPrice(value);
}else if(qName.equals("language")){
book.setLanguage(value);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
// 獲取節點值數組
value = new String(ch, start, length);
if(!value.trim().equals("")){
System.out.println("節點值:"+value);
}
}
}
⑤ java中怎麼直接獲得xml中的某個指定的節點
可以通過元素中的getText方法獲取到節點的內容。
舉例:
SAXReader sax = new SAXReader();
Document document = sax.read(reader);//reader為定義的一個字元串,可以轉換為xml
Element root = document.getRootElement();//獲取到根節點元素String str = root .getText()//獲取到節點的內容
用到的是dom4j-1.6.1.jar,需要引入的包是:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
備註:如果是多個子節點可以通過」Element xx=root .element("code")「獲取到子節點的元素,前提是需要知道子節點的名稱。
⑥ java 如何比較兩個xml的某一節點完全相同
你是要比同xml同一個節點中attribute 屬性field和lable的值嗎?還是不同xml中 各自attribute屬性field的值?
⑦ java怎麼通過xml節點的屬性獲取這個節點的值
創建解析器
SAXReader saxreader = new SAXReader();
讀取文檔
Document doc = saxreader.read(new File("url"));
獲取根
Element root = doc.getRootElement();
獲取子節點
List<Element> list = root.elements();
System.out.println(e.elementText("name"));
System.out.println(e.element("score").attributeValue("java"));