posts - 54,  comments - 1,  trackbacks - 0

 

import java.io.FileWriter;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

/**
 * 使用JDom操作XML工具
 * 
 * @author ZhuJun Create on 2005-8-17
 
*/

public class XmlUtil {

 
/**
  * 解析XML文件,生成Document对象
  * 
  * @param fileName
  * @return @throws
  *         JDOMException
  * @throws IOException
  * 
  * @author ZhuJun Create on 2005-8-17
  
*/

 
public static Document parseXml(String fileName) throws JDOMException,
   IOException 
{
  SAXBuilder builder 
= new SAXBuilder();
  
return builder.build(fileName);
 }


 
/**
  * 输出XML文件
  * 
  * @param docXML
  * @param strFilename
  * 
  * @author ZhuJun Create on 2005-8-17
  
*/

 
public static void OutputXML(Document doc, String strFilename) {
  XMLOutputter fmt 
= new XMLOutputter();
  fmt.setFormat(Format.getPrettyFormat());
  
try {
   FileWriter fwXML 
= new FileWriter(strFilename);
   fmt.output(doc, fwXML);
   fwXML.close();
  }
 catch (IOException e) {
   e.printStackTrace();
  }

 }


 
/**
  * 取得节点的值
  * 
  * @param xPath
  * @return @throws
  *         JDOMException
  * 
  * @author ZhuJun Create on 2005-8-17
  
*/

 
public static String getNodeValue(Document doc, String xPath)
   throws JDOMException 
{
  
return ((Text) XPath.selectSingleNode(doc.getRootElement(),
    
new StringBuffer(xPath).append("/text()").toString()))
    .getTextNormalize();
 }


 
/**
  * 取得节点的属性值
  * 
  * @param xPath
  * @param attrName
  * @return @throws
  *         JDOMException
  * 
  * @author ZhuJun Create on 2005-8-17
  
*/

 
public static String getAttributeValue(Document doc, String xPath,
   String attrName) throws JDOMException 
{
  Element element 
= (Element) XPath.selectSingleNode(
    doc.getRootElement(), xPath);
  
return element.getAttributeValue(attrName);
 }

}
posted on 2005-08-18 14:12 ZhuJun 阅读(327) 评论(0)  编辑  收藏 所属分类: 开发手记

只有注册用户登录后才能发表评论。


网站导航:
 

蜀中人氏,躬耕于珠海

<2005年8月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

常用链接

留言簿(2)

随笔分类(71)

随笔档案(54)

博客

文档

站点

论坛

搜索

  •  

积分与排名

  • 积分 - 49837
  • 排名 - 981

最新评论

阅读排行榜