Ⅰ 用java解析獲得xml中的值
packagecom.applet;
importjava.io.ByteArrayInputStream;
importjava.io.File;
importjava.io.StringReader;
importjava.util.Iterator;
importjava.util.List;
importorg.apache.commons.lang.StringUtils;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.SAXReader;
publicclassB{
publicstaticvoidmain(String[]args){
="<?xmlversion="1.0"encoding="utf-8"?> "
+"<EAS> "
+"<Header> "
+"<TransID>e688030e-f86f-455b-b143-58871084670b</TransID> "
+"<TransTime>2015-05-2902:12:15</TransTime> "
+"<DataType>Vendor/Customer</DataType> "
+"<OptCatalog>Single</OptCatalog> "
+"<OptType>Update/Create</OptType> "
+"<RowCount>1</RowCount> "+"</Header> "
+"<MasterData> "+"<Fieldname="UnitClass"> "
+"<!--單位分類-->2000單位分類測試一下 "+"</Field> "
+"<Fieldname="AccountGroup"> "+"<!--賬戶組--> "
+"</Field> "+"<Fieldname="Name1"> "
+"<!--單位全稱-->1111文具公司 "+"</Field> "
+"</MasterData> "+"<ChangeDetail> "
+"<ChangeFieldsname="Name1"> "
+"<OldValue>文具</OldValue> "
+"<NewValue>皮包</NewValue> "
+"<OperationType>修改</OperationType> "
+"</ChangeFields> "+"</ChangeDetail> "+"</EAS>";
//我想獲得這個xml中遍歷分別獲得
//2000單位分類測試一下,空,1111文具公司這樣的3組值,每組值中的數據用空格隔開放到數組中去,應該怎麼辦呢
try{
SAXReaderreader=newSAXReader();
Stringtxt=inputBizInfo.replaceAll(" ","");
//Documentdoc=reader.read(newStringReader(txt));
//Documentdoc=reader.read(new
//File("F:\zz\FileRecv\MyWebSocket\src\com\applet\NewFile.xml"));
//Documentdoc=reader.read(newByteArrayInputStream(txt
//.getBytes("UTF-8")));
//System.err.println(txt);
//System.err.println(root.attribute(0).getName());
Documentdoc=DocumentHelper.parseText(txt);
Elementroot=doc.getRootElement();
//System.out.println("Root:"+root.getName());
Listprojects=root.selectNodes("MasterData/Field");
//System.err.println(projects.size());
Iteratorit=projects.iterator();
while(it.hasNext()){
Elementelm=(Element)it.next();
//System.out.println("index:"+elm.attributeValue("index")+"level:"+elm.attributeValue("level")+"nickname:"+elm.attributeValue("nickname")+"country:"+elm.attributeValue("country")+"weiwang:"+elm.attributeValue("weiwang"));
//System.err.println(elm.attributeValue(elm.attribute(0).getName()));
//System.err.println(elm.getTextTrim());
Stringtext=elm.getTextTrim();
if(StringUtils.isNotBlank(text)){
String[]split=text.split("");
for(Stringstring:split){
//放入數組省略
System.err.println(string);
}
}
}
}catch(Exceptionex){
ex.printStackTrace();
}
}
}
Ⅱ java如何讀取xml節點元素值
java讀取xml節點元素,主要使用java提供的解析的工具類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字元串的元素值
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-body>jsp獲取各個節點的值:<%@ 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>
Ⅳ java讀取xml文件內容
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import
javax.xml.parsers.DocumentBuilderFactory;
import
org.w3c.dom.Document;
import org.w3c.dom.Element;
import
org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReaderTest {
public static void main(String args[]) {
Element element =
null;
// 可以使用絕對路勁
File f = new File("test.xml");
// documentBuilder為抽象不能直接實例化(將XML文件轉換為DOM文件)
DocumentBuilder db =
null;
DocumentBuilderFactory dbf = null;
try {
//
返回documentBuilderFactory對象
dbf =
DocumentBuilderFactory.newInstance();
//
返回db對象用documentBuilderFatory對象獲得返回documentBuildr對象
db =
dbf.newDocumentBuilder();
// 得到一個DOM並返回給document對象
Document dt = db.parse(f);
//
得到一個elment根元素
element = dt.getDocumentElement();
//
獲得根節點
System.out.println("根元素:" + element.getNodeName());
// 獲得根元素下的子節點
NodeList childNodes = element.getChildNodes();
// 遍歷這些子節點
for (int i = 0; i < childNodes.getLength(); i++)
{
// 獲得每個對應位置i的結點
Node node1 = childNodes.item(i);
if
("Account".equals(node1.getNodeName())) {
//
如果節點的名稱為"Account",則輸出Account元素屬性type
System.out.println("\r\n找到一篇賬號.
所屬區域: " + node1.getAttributes().getNamedItem("type").getNodeValue() + ".
");
// 獲得<Accounts>下的節點
NodeList nodeDetail =
node1.getChildNodes();
// 遍歷<Accounts>下的節點
for (int j = 0;
j < nodeDetail.getLength(); j++) {
//
獲得<Accounts>元素每一個節點
Node detail = nodeDetail.item(j);
if
("code".equals(detail.getNodeName())) //
輸出code
System.out.println("卡號: " +
detail.getTextContent());
else if ("pass".equals(detail.getNodeName()))
// 輸出pass
System.out.println("密碼: " +
detail.getTextContent());
else if ("name".equals(detail.getNodeName()))
// 輸出name
System.out.println("姓名: " +
detail.getTextContent());
else if
("money".equals(detail.getNodeName())) //
輸出money
System.out.println("余額: " +
detail.getTextContent());
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Ⅳ java 怎麼讀取xml裡面的值
java讀取xml信息常用技術有dom解析和dom4J解析
dom4j是最常用的java解析xml技術回,在使用時需答要下載dom4j.jar
具體解析方法可以參考一下內容
xml結構
<books>
<book id="001">
<title>Harry Potter</title>
<author>J K. Rowling</author>
</book>
<book id="002">
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</books>
Ⅵ java如何從xml文件中讀取一個值
java讀取xml信息常用技術有dom解析和dom4J解析
dom4j是最常用的java解析xml技術,在使用時需要下載dom4j.jar
具體解析方法可以參考一下內容
xml結構
<books>
<bookid="001">
<title>HarryPotter</title>
<author>JK.Rowling</author>
</book>
<bookid="002">
<title>LearningXML</title>
<author>ErikT.Ray</author>
</book>
</books>
解析為List集合
importjava.io.File;
importjava.util.List;
importorg.dom4j.Attribute;
importorg.dom4j.Document;
importorg.dom4j.Element;
importorg.dom4j.io.SAXReader;
publicclassDemo{
publicstaticvoidmain(String[]args)throwsException{
SAXReaderreader=newSAXReader();
Filefile=newFile("books.xml");
Documentdocument=reader.read(file);
Elementroot=document.getRootElement();
List<Element>childElements=root.elements();
for(Elementchild:childElements){
//未知屬性名情況下
/*List<Attribute>attributeList=child.attributes();
for(Attributeattr:attributeList){
System.out.println(attr.getName()+":"+attr.getValue());
}*/
//已知屬性名情況下
System.out.println("id:"+child.attributeValue("id"));
//未知子元素名情況下
/*List<Element>elementList=child.elements();
for(Elementele: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();
}
}
}