import javaioIOException;
import javautilIterator;import orgdom4j;
import orgdom4jioXMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSamplecreateDocument();
try{
dom4jSampleFileWrite(document);
Document documentStr = dom4jSampleStringToXML("<China>I Love!</China>");
dom4jSampleXMLWrite(documentStr);
Element legend = dom4jSampleFindElement(document);
Systemoutprintln(legendgetText());
}
catch(Exception e)
{
}
}
/
Create a XML Document
/
public Document createDocument()
{
Document document = DocumentHelpercreateDocument();
Element root = documentaddElement("root");
Element author1 = rootaddElement("Lynch");
author1addAttribute("Age","25");
author1addAttribute("Country","China");
author1addText("I am great!");
Element author2 = rootaddElement("Legend");
author2addAttribute("Age","25");
author2addAttribute("Country","China");
author2addText("I am great!too!");
return document;
}
/
Create a XML document through String
/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelperparseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = documentgetRootElement();
Element legend = null;
for(Iterator i=rootelementIterator("legend");ihasNext();)
{
legend = (Element)inext();
}
return legend;
}
/
Write a XML file
/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSamplexml");
documentwrite(out);
outclose();
}
/
Write a XML format file
/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStrxml"));
writerwrite(document);
writerclose();
}
}如果是在纯java类中
String dirpath = SystemgetProperty("userdir"); String xmlFile = dirpath + "/WebRoot/WEB-INF/serverxml"; String fileName = dirPath + "/serverxml";
在servlet中
String dirPath = getServletContext()getRealPath( "/WEB-INF"); String xmlFile = dirPath + "/serverxml";
在jsp中
String dirPath= requestgetServletContext()getRealPath("/WEB-INF"); String xmlFile = dirPath+"serverxml";
我自己的xml文件是放在WebRoot/WEB_INF下
参考:
>如果你发布项目的话,绝对路径是不行的(那是你本地电脑上的路径)
这时应该用类加载器来读取类的路径,你可以把xml文件放到src目录下,这个目录时存放源代码和字节码的
classgetClassloaderget,,,,,,
class表示当前类的class对象,getClassLoader获得类加载器
后面的一个方法我记不太清了,是获取IO流的方法,你找找看
这种方法即使你发布工程到tomcat上也没问题如果spring的配置文件在src路径下,在webxml中要加载配置文件,
路径应该是这样:classpath:spring(文件名字)xml
如果在其他路径下,就要写绝对路径了。把你的XML toString,变成字符串,保存到文件就可以了 ,给你提供一个将字符串保存成文件的方法
public static void saveFile(String fileName, String content) {
try {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName, true),"UTF-8");
oswwrite(content);
oswclose();
} catch (IOException e) {
eprintStackTrace();
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)