⑴ java怎麼解析xml文件
Stringxml="<xml><ToUserName><![CDATA[toUser]]></ToUserName>"沖舉簡
+"<FromUserName><![CDATA[fromUser]]>答拆</FromUserName>"
+"<CreateTime>12345678</CreateTime>"
+"<MsgType><![CDATA[text]]></MsgType>"
+"<Content>散褲<![CDATA[你好]]></Content></xml>";
try{
//載入xml字元串
org.dom4j.Documentdocument=org.dom4j.DocumentHelper.parseText(xml);
//獲取根節點
org.dom4j.Elementroot=document.getRootElement();
//獲取值==toUser
StringtoUserName=root.elementText("ToUserName");
System.out.println(toUserName);
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
⑵ 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文件
用java自帶的就可以,有問題可以問我
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
//構造
public XMLUtil(String name) throws ParserConfigurationException {
filename = name;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
/**
* 保存到文件
*/
public void toSave() {
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
StreamResult result = new StreamResult(pw);
transformer.transform(source, result);
} catch (TransformerException mye) {
mye.printStackTrace();
} catch (IOException exp) {
exp.printStackTrace();。
⑷ 如何用Java實現對xml文件的讀取和寫入以及保存
直接附源碼import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;import org.dom4j.*;
import org.dom4j.io.XMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSample.createDocument();
try{
dom4jSample.FileWrite(document);
Document documentStr = dom4jSample.StringToXML("<China>I Love!</China>");
dom4jSample.XMLWrite(documentStr);
Element legend = dom4jSample.FindElement(document);
System.out.println(legend.getText());
}
catch(Exception e)
{
}
}
/*
* Create a XML Document
*/
public Document createDocument()
{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age","25");
author1.addAttribute("Country","China");
author1.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age","25");
author2.addAttribute("Country","China");
author2.addText("I am great!too!");
return document;
}
/*
* Create a XML document through String
*/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelper.parseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = document.getRootElement();
Element legend = null;
for(Iterator i=root.elementIterator("legend");i.hasNext();)
{
legend = (Element)i.next();
}
return legend;
}
/*
* Write a XML file
*/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSample.xml");
document.write(out);
out.close();
}
/*
* Write a XML format file
*/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStr.xml"));
writer.write(document);
writer.close();
}
}
⑸ java如何組裝xml報文
可以用 我給你的方式組合xml報文