
正文
xml读取java代码 java从xml中读取数据
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在Java中如何读取XML字符串的元素值
java读取xml节点元素,主要使用java提供的解析xml的工具类SAXParserFactory,如下代码:
package xml.xmlreader;import java.io.File;import java.net.URL;import java.util.Properties;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;public class CFGParser {//解析xml文件的工具类 private Properties props; public Properties getProps() { return props; } public void setProps(Properties props) { this.props = props; } public void parse(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); URL confURL = super.getClass().getClassLoader().getResource(filename); if (confURL == null) { System.out.println("Can't find configration file."); return; } try { parser.parse(confURL.toString(), handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } } public void parseFile(String filename) throws Exception { CFGHandler handler = new CFGHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); SAXParser parser = factory.newSAXParser(); File f = new File(filename); if ((f == null) || (!f.exists())) return; try { parser.parse(f, handler); this.props = handler.getProps(); } finally { factory = null; parser = null; handler = null; } }}package xml.xmlreader;import java.util.Properties;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler; public class CFGHandler extends DefaultHandler{ private Properties props; private String currentSet; private String currentName; private StringBuffer currentValue = new StringBuffer(); public CFGHandler() { this.props = new Properties(); } public Properties getProps() { return this.props; } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { this.currentValue.delete(0, this.currentValue.length()); this.currentName = qName; } public void characters(char[] ch, int start, int length) throws SAXException { this.currentValue.append(ch, start, length); } public void endElement(String uri, String localName, String qName) throws SAXException { this.props.put(qName.toLowerCase(), this.currentValue.toString().trim()); }}xml文件 ?xml version="1.0" encoding="UTF-8"?xml-body refresh_userlist desc="用户列表刷新间隔时间(秒)"6/refresh_userlist refresh_message desc="短消息刷新间隔时间(秒)"10/refresh_message morningbegin desc="上午上班时间"23:00/morningbegin morningend desc="上午下班时间"12:00/morningend afternoonbegin desc="下午上班时间"18:00/afternoonbegin/xml-bodyjsp获取各个节点的值:%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%html jsp:useBean id="cfgp" scope="page" class="xml.xmlreader.CFGParser"/jsp:useBean body % cfgp.parse("kaoqin.xml"); Properties pro = cfgp.getProps(); String stTime = pro.getProperty("morningbegin"); String edTime = pro.getProperty("morningend"); String afternoonbegin = pro.getProperty("afternoonbegin"); out.println(stTime+"\n"+edTime+"\n"+afternoonbegin); System.out.println(stTime+"\n"+edTime+"\n"+afternoonbegin); % /body/html
相关问答
Q1: JAVA读取XML文件
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class Xml {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("E:\\新建 文本文档 (3).xml"));
Element rootElement = document.getDocumentElement();
NodeList list = rootElement.getElementsByTagName("Header");
Element element = (Element) list.item(0);
System.out.println(element.getChildNodes().item(0).getNodeValue());
} catch (Exception e) {
System.out.println("exception:" + e.getMessage());
}
}
}
Q2: 200分求帮写个JAVA读取XML的代码
解析xml方法,供参考,希望能帮助lz点
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package xml;
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
public class MyXMLReader {
public String libPath = null;
public String filePath;
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getLibPath() {
return libPath;
}
//得到用户xml中各个节点的值
public void getPathValue(String xmlPath) throws ParserConfigurationException, SAXException, IOException {
File f = new File(xmlPath);
FileInputStream fs=new FileInputStream(f);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList n2 = doc.getDocumentElement().getElementsByTagName("context-param");
for (int i = 0; i n2.getLength(); i++) {
String name = doc.getElementsByTagName("param-name").item(i).getFirstChild().getNodeValue();
String value = doc.getElementsByTagName("param-value").item(i).getFirstChild().getNodeValue();
if (name.equals("libPath")) {
libPath = value;
}
}
}
//将要更新文件中的值替换掉
public void setPathValue() throws ParserConfigurationException, SAXException, IOException {
String xml="./hzims/Tomcat6/webapps/ROOT/WEB-INF/web.xml";
File f = new File(xml);
FileInputStream fs=new FileInputStream(f);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList n2 = doc.getDocumentElement().getElementsByTagName("context-param");
for (int i = 0; i n2.getLength(); i++) {
String name = doc.getElementsByTagName("param-name").item(i).getFirstChild().getNodeValue();
String value = doc.getElementsByTagName("param-value").item(i).getFirstChild().getNodeValue();
if (name.equals("libPath")) {
doc.getElementsByTagName("param-value").item(i).getFirstChild().setNodeValue(libPath);
try {
reSetValue(doc,"./hzims/Tomcat6/webapps/ROOT/WEB-INF/web.xml" );
} catch (FileNotFoundException ex) {
Logger.getLogger(MyXMLReader.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerConfigurationException ex) {
Logger.getLogger(MyXMLReader.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(MyXMLReader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void reSetValue(Document doc, String path) throws FileNotFoundException, IOException, TransformerConfigurationException,
TransformerException {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
//设置输出的encoding为改变gb2312
transformer.setOutputProperty("encoding", "gb2312");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(path));
transformer.transform(source, result);
}
}
xml读取java代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java从xml中读取数据、xml读取java代码的信息别忘了在本站进行查找喔。






