本文目錄一覽:
java如何從xml文件中讀取一個值
java讀取xml信息常用技術有dom解析和dom4J解析
dom4j是最常用的java解析xml技術,在使用時需要下載dom4j.jar
具體解析方法可以參考一下內容
xml結構
books
book id=”001″
titleHarry Potter/title
authorJ K. Rowling/author
/book
book id=”002″
titleLearning XML/title
authorErik T. Ray/author
/book
/books
解析為List集合
import java.io.File;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Demo {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
File file = new File(“books.xml”);
Document document = reader.read(file);
Element root = document.getRootElement();
ListElement childElements = root.elements();
for (Element child : childElements) {
//未知屬性名情況下
/*ListAttribute attributeList = child.attributes();
for (Attribute attr : attributeList) {
System.out.println(attr.getName() + “: ” + attr.getValue());
}*/
//已知屬性名情況下
System.out.println(“id: ” + child.attributeValue(“id”));
//未知子元素名情況下
/*ListElement elementList = child.elements();
for (Element ele : elementList) {
System.out.println(ele.getName() + “: ” + ele.getText());
}
System.out.println();*/
//已知子元素名的情況下
System.out.println(“title” + child.elementText(“title”));
System.out.println(“author” + child.elementText(“author”));
//這行是為了格式化美觀而存在
System.out.println();
}
}
}
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文件
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlTester {
public static void main(String[] args) throws DocumentException {
// 使用了dom4j解析xml
// 讀取目錄下用來測試的test.xml文件,取得xml主內容
Document document = new SAXReader().read(“src/abc/test.xml”).getDocument();
int i = 1;
// 遍歷文檔根節點(wuxialist)下的子節點列表,即txtbook節點的集合
for(Element txtbook : (ListElement)document.getRootElement().elements()){
//取得txtbook節點下的name節點的內容
System.out.println(i+”.”+txtbook.element(“name”).getText());
i++; //原來這裡少些了這一行,先補上
}
}
}
java如何讀取xml文件
xml解析還是用dom4j方便,
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XMLPaser {
public static void main(String[] args) {
paserXML();
}
public static void paserXML(){
SAXReader reader = new SAXReader();
try {
// 讀取XML文件
Document doc = reader.read(“NewFile.xml”);
Element root = doc.getRootElement();
System.out.println(root.getName());
ListElement param = root.elements();
for (Element element : param) {
if(element.attributeValue(“name”).equals(“a”)){
System.out.println(element.getText());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/151253.html