package xml;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class TestXML ...{
//创建XML文档
public static Document createDocument() ...{
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );
Element author1 = root.addElement( "author" )
.addAttribute( "name", "James" )
.addAttribute( "location", "UK" )
.addText( "James Strachan" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "US" )
.addText( "Bob McWhirter" );
return document;
}
//将文档内容输出到文件或控制台
public static void write(Document document) throws IOException ...{
// lets write to a file
XMLWriter writer = new XMLWriter(
new FileWriter( "output.xml" )
);
writer.write( document );
writer.close();
// Pretty print the document to System.out
OutputFormat format = OutputFormat.createPrettyPrint();
writer = new XMLWriter( System.out, format );
writer.write( document );
// Compact format to System.out
format = OutputFormat.createCompactFormat();
writer = new XMLWriter( System.out, format );
writer.write( document );
}
//解析XML文件成Document ,url为文件路径
public static Document parse(String url) throws DocumentException ...{
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
//read Docment内容
public static void read(Document document) throws DocumentException ...{
Element root = document.getRootElement();
// 从XML的根结点开始遍历
for ( Iterator i = root.elementIterator(); i.hasNext(); ) ...{
Element element = (Element) i.next();
System.out.println(element.getName()+":"+element.getText());
}
/**//* // iterate through child elements of root with element name "foo"
for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) {
Element foo = (Element) i.next();
// do something
}
// iterate through attributes of root
for ( Iterator i = root.attributeIterator(); i.hasNext(); ) {
Attribute attribute = (Attribute) i.next();
// do something
}*/
}
//将document转化为String
public static String XmlToString(Document document)...{
return document.asXML();
}
//将document转化为String
public static Document StringToDocument(String text)...{
try ...{
return DocumentHelper.parseText(text);
} catch (DocumentException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws IOException, DocumentException ...{
// write(parse("E:/WebService/XFire/example/XFire/output.xml"));
String str="<?xml version='1.0' encoding='utf-16'?> "+
"<CurrentWeather>"+
"<Location>Shanghai / Hongqiao, China (ZSSS) 31-10N 121-26E 3M</Location>"+
"<Time>Aug 22, 2007 - 09:00 PM EDT / 2007.08.23 0100 UTC</Time>"+
"<Wind> from the ESE (110 degrees) at 7 MPH (6 KT) (direction variable):0</Wind>"+
"<Visibility> 4 mile(s):0</Visibility>"+
"<SkyConditions> mostly clear</SkyConditions>"+
"<Temperature> 87 F (31 C)</Temperature>"+
"<DewPoint> 78 F (26 C)</DewPoint>"+
"<RelativeHumidity> 74%</RelativeHumidity>"+
"<Pressure> 29.77 in. Hg (1008 hPa)</Pressure>"+
"<Status>Success</Status>"+
"</CurrentWeather>";
write(StringToDocument(str));
}
}
SAX解析xml
1、使用绝对路径
// 解析XML文件成Document ,url为文件路径
SAXReader reader = new SAXReader();
Document document = null;
String xmlFilePath = "d:/serialComm.xml";
document = reader.read(xmlFilePath);
InitSMSCat.log.info("串口配置文件的目录:"+xmlFilePath);
if(document == null)
{
InitSMSCat.log.info("配置文件serialComm.xml读取发生错误!!!");
throw new Exception("配置文件serialComm.xml读取发生错误!!!");
}
// read Docment内容
Element root = document.getRootElement();
// 从XML的根结点开始遍历
for (Iterator i = root.elementIterator(); i.hasNext();)
{
Element element = (Element) i.next();
if(element.getName().equals("comm")) comm = element.getText();
}
2、使用环境变量
// 解析XML文件成Document ,url为文件路径
SAXReader reader = new SAXReader();
Document document = null;
InitSMSCat.log.info("环境变量SMS_HOME = "+System.getenv("SMS_HOME"));
String xmlFilePath = "";
if(Utility.getOsName().equals("windows"))
xmlFilePath = System.getenv("SMS_HOME")+"";
if(Utility.getOsName().equals("linux"))
xmlFilePath = (System.getenv("SMS_HOME")+"/config/serialComm.xml").replace("\\", "/");
document = reader.read(xmlFilePath);
InitSMSCat.log.info("串口配置文件的目录:"+xmlFilePath);
if(document == null)
{
InitSMSCat.log.info("配置文件serialComm.xml读取发生错误!!!");
throw new Exception("配置文件serialComm.xml读取发生错误!!!");
}
// read Docment内容
Element root = document.getRootElement();
// 从XML的根结点开始遍历
for (Iterator i = root.elementIterator(); i.hasNext();)
{
Element element = (Element) i.next();
if(element.getName().equals("comm")) comm = element.getText();
}
3、读取jar包中的xml文件
// 解析XML文件成Document ,url为文件路径
SAXReader reader = new SAXReader();
Document document = null;
document = reader.read(this.getClass().getResourceAsStream("/serialComm.xml"));
if(document == null)
{
InitSMSCat.log.info("配置文件serialComm.xml读取发生错误!!!");
throw new Exception("配置文件serialComm.xml读取发生错误!!!");
}
// read Docment内容
Element root = document.getRootElement();
// 从XML的根结点开始遍历
for (Iterator i = root.elementIterator(); i.hasNext();)
{
Element element = (Element) i.next();
if(element.getName().equals("comm")) comm = element.getText();
}