<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    kingpub

    海內存知己,博客若比鄰

     

    用DOM/JDOM解析XML文件

    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.List;

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

    /**
    * Jdom解析XML
    *
    * @FileName:XMLUtil.java
    * @author Javer.Leo (QQ:84831612)
    * @date 2006-8-16
    */
    public final class XMLUtil
    {
    /**
    * 定義xml編碼方式
    */
    public static final String ENCODE_GBK = "GBK";
    public static final String ENCODE_UTF8 = "UTF-8";
    public static final String ENCODE_UTF16 = "UTF-16";
    public static final String ENCODE_GB2312 = "gb2312";
    public static final String ENCODE_ISO8859 = "ISO8859-1";

    private static Format format = Format.getPrettyFormat();

    static {
    format.setEncoding(ENCODE_UTF8);
    }

    /**
    * Read and parse an xml document from the file at xml/sample.xml.
    * This method corresponds to the code in Listing 7.
    * @param filePath 要解析的xml文件路徑
    * @return the JDOM document parsed from the file.
    * @throws IOException
    */
    public static Document readDocument(String filePath) throws IOException {
    try {
    SAXBuilder builder = new SAXBuilder(false);
    Document anotherDocument = builder.build(new File(filePath));
    return anotherDocument;
    } catch(Exception e) {
    e.printStackTrace();
    throw new IOException(e.getMessage());
    }
    }

    /**
    * Read and parse an xml document from the file at xml/sample.xml.
    * This method corresponds to the code in Listing 7.
    * @param filePath 要解析的xml文件路徑
    * @return the JDOM document parsed from the file.
    * @throws IOException
    */
    public static Document readDocument(InputStream input) throws IOException {
    try {
    SAXBuilder builder = new SAXBuilder(false);
    Document anotherDocument = builder.build(input);
    input.close();
    return anotherDocument;
    } catch(Exception e) {
    throw new IOException(e.getMessage());
    }
    }

    /**
    * 讀取xml文件
    * @param srcFile 目標文件
    * @return DOM對象
    * @throws IOException
    */
    public static Document readDocument(File srcFile) throws IOException {
    try {
    SAXBuilder builder = new SAXBuilder();
    Document anotherDocument = builder.build(srcFile);
    return anotherDocument;
    } catch(Exception e) {
    throw new IOException(e.getMessage());
    }
    }

    /**
    * 向指定的文檔模型添加指定元素標識名稱的元素
    * @param document 要添加元素的文檔模型
    * @param elementName 要添加的元素標識名稱
    * @param parentElementPath 父元素路徑
    * @return
    */
    public static void addElement(Object document,String parentElementPath,String elementName){
    try{
    Element parentElement;
    parentElement = (Element)XPath.selectSingleNode(document,parentElementPath);
    Element newElement = new Element(elementName);
    parentElement.addContent(newElement);
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }

    /**
    * 向指定的文檔模型添加已創建元素
    * @param document 要添加元素的文檔模型
    * @param newElement 要添加的新元素
    * @param parentElementPath 父元素路徑
    * @return
    */
    public static void addElement(Object document,String parentElementPath,Element newElement){
    try{
    Element parentElement;
    parentElement = (Element)XPath.selectSingleNode(document,parentElementPath);
    parentElement.addContent(newElement);
    } catch (Exception e1) {
    e1.printStackTrace();
    }
    }

    /**
    * 獲取指定子元素路徑的子元素列表
    * @param document the JDOM document built from Listing 2
    * @param visitedNodeName 指定要訪問的子節點元素名稱
    * @return 返回指定元素路徑的子元素列表
    */
    public static List getChildrenElement(Object document,String visitedNodeName) {
    List visitElements = null;
    try {
    visitElements = XPath.selectNodes(document,visitedNodeName);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return visitElements;
    }

    /**
    * 獲取指定子元素路徑名稱和屬性名稱及值的元素
    * @param document the JDOM document built from Listing 2
    * @param visitedNodeName 指定要訪問的子節點元素名稱
    * @param attributeName 屬性名稱
    * @param attributeValue 屬性值
    * @return 返回指定的元素
    */
    public static Element getChildElement(Object document,String visitedNodeName,String attributeName,String attributeValue) {
    Element visitElement = null;
    try {
    visitElement = (Element)XPath.selectSingleNode(document,visitedNodeName+"[@"+attributeName+"='"+attributeValue+"']");
    } catch (Exception e) {
    e.printStackTrace();
    }
    return visitElement;
    }

    /**
    * 獲取指定子元素路徑名稱和屬性名稱及值的元素
    * @param document the JDOM document built from Listing 2
    * @param visitedNodeName 指定要訪問的子節點元素名稱
    * @return 返回指定的元素
    */
    public static Element getChildElement(Object document,String visitedNodeName) {
    Element visitElement = null;
    try {
    visitElement = (Element)XPath.selectSingleNode(document,visitedNodeName);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return visitElement;
    }

    /**
    * 刪除指定元素節點路徑的元素
    * @param removeNodeName 要刪除的元素路徑
    * @param document xml文件對應的文檔模型
    */
    public static boolean removeChildElement(Object document,String removeNodeName) {
    Element visitElement = null;
    boolean isRemoved = false;
    try {
    visitElement = (Element)XPath.selectSingleNode(document,removeNodeName);
    if(visitElement != null)
    isRemoved = visitElement.getParentElement().removeContent(visitElement);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return isRemoved;
    }

    /**
    * 刪除指定屬性的元素
    * @param document xml文件對應的文檔模型
    * @param removeNodeName 要刪除的節點元素路徑
    * @param attributeName 屬性名稱
    * @param attributeValue 屬性值
    * @return
    */
    public static boolean removeChildElement(Object document,String removeNodeName ,String attributeName,String attributeValue) {
    List removeElements = null;
    Element visitElement = null;
    boolean isRemoved = false;
    try {
    removeElements = XPath.selectNodes(document,removeNodeName+"[@"+attributeName+"='"+attributeValue+"']");
    if(removeElements != null){
    for (int i = 0; i < removeElements.size(); i++) {
    visitElement = (Element) removeElements.get(i);
    isRemoved = visitElement.getParentElement().removeContent(visitElement);
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return isRemoved;
    }

    /**
    * 將xml文檔模型輸出到標準輸出設備(屏幕)
    * @param document 指定的xml文檔模型
    */
    public static void outputDocument(Document document) {
    format.setIndent(" ");
    format.setExpandEmptyElements(false);
    try {
    XMLOutputter outputter = new XMLOutputter(format);
    outputter.output(document, System.out);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * 將xml文檔模型輸出到標準輸出設備(流)
    * @param document 指定的xml文檔模型
    */
    public static void outputDocument(Document document,OutputStream output) {
    format.setIndent(" ");
    format.setExpandEmptyElements(false);
    try {
    XMLOutputter outputter = new XMLOutputter(format);
    outputter.output(document, output);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * 將xml文檔模型輸出到指定文件
    * @param document 指定的xml文檔模型
    * @param outputFilePath 輸出文件路徑
    */
    public static void outputDocumentToFile(Document document,String outputFilePath) {
    outputDocumentToFile(document,outputFilePath,ENCODE_GB2312);
    }

    /**
    * 將xml文檔模型輸出到指定文件
    * @param document 指定的xml文檔模型
    * @param outputFilePath 輸出文件路徑
    * @param encodingMode 編碼方式
    */
    public static void outputDocumentToFile(Document document,String outputFilePath,String encodingMode) {
    format.setEncoding(encodingMode);
    format.setIndent(" ");
    format.setExpandEmptyElements(false);
    FileWriter writer = null;

    try {
    XMLOutputter outputter = new XMLOutputter(format);
    writer = new FileWriter(outputFilePath);
    outputter.output(document, writer);
    writer.close();

    }catch(Exception ep) {
    ep.printStackTrace();
    }
    finally{
    try {
    if(writer != null)
    writer.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    }
    }

    /**
    * 將將xml文檔模型輸出到指定字符串
    * @param document 指定的xml文檔模型
    * @return 返回document的內容
    */
    public static String outputDocumentString(Document document){

    return outputDocumentString(document,ENCODE_GBK);
    }

    /**
    * 將將xml文檔模型輸出到指定字符串
    * @param document 指定的xml文檔模型
    * @param encodingMode 編碼格式
    * @return 返回document的內容
    */
    public static String outputDocumentString(Document document,String encodingMode){
    format.setEncoding(encodingMode);
    format.setIndent(" ");
    format.setExpandEmptyElements(false);
    XMLOutputter outputter = new XMLOutputter(format);
    return outputter.outputString(document);
    }

    /**
    * This method takes a JDOM document in memory, an xsl file at xml/car.xsl,
    * and outputs the results to stdout.
    * This method corresponds to Listing 9.
    * @param myDocument the JDOM document built from Listing 2.
    */
    // public static void executeXSL(Document myDocument) {
    // try {
    // TransformerFactory tFactory = TransformerFactory.newInstance();
    // // Make the input sources for the XML and XSLT documents
    // org.jdom.output.DOMOutputter outputter = new org.jdom.output.DOMOutputter();
    // org.w3c.dom.Document domDocument = outputter.output(myDocument);
    // javax.xml.transform.Source xmlSource = new javax.xml.transform.dom.DOMSource(domDocument);
    // StreamSource xsltSource = new StreamSource(new FileInputStream("car.xsl"));
    // //Make the output result for the finished document
    // /*
    // * Note that here we are just going to output the results to the
    // * System.out, since we don't actually have a HTTPResponse object
    // * in this example
    // */
    // //StreamResult xmlResult = new StreamResult(response.getOutputStream());
    // StreamResult xmlResult = new StreamResult(System.out);
    // //Get a XSLT transformer
    // Transformer transformer = tFactory.newTransformer(xsltSource);
    // //do the transform
    // transformer.transform(xmlSource, xmlResult);
    // } catch(FileNotFoundException e) {
    // e.printStackTrace();
    // } catch(TransformerConfigurationException e) {
    // e.printStackTrace();
    // } catch(TransformerException e) {
    // e.printStackTrace();
    // } catch(org.jdom.JDOMException e) {
    // e.printStackTrace();
    // }
    // }

    /**
    * 修改指定節點元素的屬性
    * @param document
    * @param nodePath
    * @param name
    * @param value
    */
    public static void setElementAttributeValue(Object document,String nodePath,String name,String value){
    try {
    ((Element)XPath.selectSingleNode(document,nodePath)).setAttribute(name,value);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * 修改指定節點元素的屬性
    * @param document
    * @param nodePath
    * @param attrName
    * @param attrValue
    * @param name
    * @param value
    */
    public static void setElementAttributeValue(Object document,String nodePath,String attrName,String attrValue,String name,String value){
    nodePath +="[@" + attrName + "='" + attrValue + "']";
    setElementAttributeValue(document,nodePath,name,value);
    }
    /**
    * 修改指定節點元素的內容
    * @param document
    * @param nodePath
    * @param text
    */
    public static void setElementText(Object document,String nodePath,String text){
    try {
    ((Element)XPath.selectSingleNode(document,nodePath)).setText(text);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    /**
    * 修改指定節點元素的內容
    * @param document
    * @param nodePath
    * @param attrName
    * @param attrValue
    * @param text
    */
    public static void setElementText(Object document,String nodePath,String attrName,String attrValue,String text){
    nodePath +="[@" + attrName + "='" + attrValue + "']";
    setElementText(document,nodePath,text);
    }

    /**
    * 設置xml的編碼格式
    * @param encode
    */
    public static void setEncoding(String encode){
    format.setEncoding(encode);

    }

    /**
    * 用DTD文檔類型定義校驗xml文檔
    * @param content
    * @return
    */
    // public static boolean validate(){
    // SAXBuilder builder = new SAXBuilder(true);
    // try{
    // // Jdom complains about the document even though it is valid
    // ByteArrayInputStream bais=new ByteArrayInputStream(content.getBytes());
    // builder.build(bais);
    // return true;
    //
    // } catch (Exception e) {
    //
    // return false;
    //
    // }
    //
    // }

    public static void main(String[] args) throws Exception
    {
    Document doc = XMLUtil.readDocument("test.xml");
    List shapes = XMLUtil.getChildrenElement(doc, "javer/leo/example");
    for(int i=0;i {
    System.out.println(XMLUtil.getChildElement(shapes.get(i), "id").getText());
    }
    }
    }

    posted on 2006-08-22 16:07 xiaofeng 閱讀(540) 評論(0)  編輯  收藏


    只有注冊用戶登錄后才能發表評論。


    網站導航:
     

    導航

    統計

    常用鏈接

    留言簿(2)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    收藏夾

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 中文字幕免费观看视频| 免费在线人人电影网| 一区二区三区观看免费中文视频在线播放 | 亚洲精品无码你懂的| 日韩一区二区a片免费观看| 亚洲午夜精品在线| 色窝窝免费一区二区三区| 亚洲av永久综合在线观看尤物| 国产男女爽爽爽爽爽免费视频| 亚洲一区在线视频观看| 操美女视频免费网站| 亚洲成a人无码亚洲成av无码| 色吊丝永久在线观看最新免费| 久久精品国产亚洲AV未满十八| 伊人久久亚洲综合影院| 深夜免费在线视频| 国产亚洲精品激情都市| 无码国产精品一区二区免费vr| 亚洲精品乱码久久久久久下载 | 中字幕视频在线永久在线观看免费| 亚洲午夜未满十八勿入| 免费福利视频导航| 亚洲av无码成人精品国产| 国产精品亚洲综合专区片高清久久久| 大妹子影视剧在线观看全集免费| 久久精品国产96精品亚洲| 91在线视频免费看| 四虎国产精品成人免费久久| 亚洲AV综合色区无码一区爱AV| 国产一卡二卡四卡免费| 免费看一级毛片在线观看精品视频| 亚洲国产精品无码久久久不卡| 99久久这里只精品国产免费| 黄色免费在线观看网址| 亚洲成熟xxxxx电影| 免费黄网在线观看| 国产免费无码AV片在线观看不卡| 久久精品国产亚洲αv忘忧草 | 国产一卡二卡≡卡四卡免费乱码| 99久久精品毛片免费播放| 亚洲三级在线免费观看|