搜尋
首頁後端開發XML/RSS教程Java&Xml教學(七)使用JDOM修改XML檔案內容

JDOM提供了非常靈活的方式操作XML文件,使用JDOM非常簡單且程式碼簡潔可讀性強。前面我們學習如何使用JDOM解析XML文件,本節介紹如何使用JDOM修改XML文件內容。

在這個教學中,我們準備對下面的XML檔案進行修改:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>

我們將改變xml中每個Employee元素:
1.修改所有name元素,使它的內容全部變成大寫。
2.在gender(性別)為Male(男)的id屬性值後追加M,gender(性別)為Female(女) 的id屬性值後追加F。
3.刪除gender元素。
4.為每個Employee元素增加salary(薪水)子元素,預設值為1000。
下面是程式碼:
JDOMXMLEditor.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMXMLEditor {

    public static void main(String[] args) throws JDOMException, IOException {        
    final Namespace ns = Namespace.getNamespace("http://www.journaldev.com/employees");        
    //Get the JDOM document
        org.jdom2.Document doc = useSAXParser("employees.xml");        
        //Get list of Employee element
        Element rootElement = doc.getRootElement();
        List<Element> listEmpElement = rootElement.getChildren("Employee", ns);        
        //loop through to edit every Employee element
        for (Element empElement : listEmpElement) {            
        //change the name to BLOCK letters
            String name = empElement.getChildText("name", ns);            
            if (name != null)
                empElement.getChild("name", ns).setText(name.toUpperCase());            
                //edit the ID attribute based on Gender
            String gender = empElement.getChildText("gender", ns);            
            if (gender != null && gender.equalsIgnoreCase("female")) {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "F");
            } else {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "M");
            }            
            //remove gender element as it&#39;s not needed anymore
            empElement.removeChild("gender", ns);            
            //add salary element with default value to every employee
            empElement.addContent(new Element("salary", ns).setText("1000"));
        }        
        //document is processed and edited successfully, lets save it in new file
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());        
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));
    }    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();        
        return saxBuilder.build(new File(fileName));
    }

}

需要注意的是上面程式碼使用命名空間取得所有元素,執行程式輸出XML檔案內容:
employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1M">
    <age>25</age>
    <name>PANKAJ</name>
    <role>Java Developer</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="2F">
    <age>34</age>
    <name>MONA</name>
    <role>Manager</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="3M">
    <age>45</age>
    <name>DAVE</name>
    <role>Support</role>
    <salary>1000</salary>
  </Employee></Employees>

JDOM提供了非常靈活的方式操作XML文件,使用JDOM非常簡單而且程式碼簡潔可讀性強。前面我們學習如何使用JDOM解析XML文件,本節介紹如何使用JDOM修改XML文件內容。
在這個教學中,我們準備對下面的XML檔案進行修改:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>

我們將改變xml中每個Employee元素:
1.修改所有name元素,使它的內容全部變成大寫。
2.在gender(性別)為Male(男)的id屬性值後追加M,gender(性別)為Female(女) 的id屬性值後追加F。
3.刪除gender元素。
4.為每個Employee元素增加salary(薪水)子元素,預設值為1000。
下面是程式碼:
JDOMXMLEditor.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMXMLEditor {

    public static void main(String[] args) throws JDOMException, IOException {        
    final Namespace ns = Namespace.getNamespace("http://www.journaldev.com/employees");        
    //Get the JDOM document
        org.jdom2.Document doc = useSAXParser("employees.xml");        
        //Get list of Employee element
        Element rootElement = doc.getRootElement();
        List<Element> listEmpElement = rootElement.getChildren("Employee", ns);        
        //loop through to edit every Employee element
        for (Element empElement : listEmpElement) {            
        //change the name to BLOCK letters
            String name = empElement.getChildText("name", ns);            
            if (name != null)
                empElement.getChild("name", ns).setText(name.toUpperCase());            
                //edit the ID attribute based on Gender
            String gender = empElement.getChildText("gender", ns);            
            if (gender != null && gender.equalsIgnoreCase("female")) {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "F");
            } else {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "M");
            }            
            //remove gender element as it&#39;s not needed anymore
            empElement.removeChild("gender", ns);            
            //add salary element with default value to every employee
            empElement.addContent(new Element("salary", ns).setText("1000"));
        }        //document is processed and edited successfully, lets save it in new file
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());        
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));
    }    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();        
        return saxBuilder.build(new File(fileName));
    }

}

需要注意的是上面程式碼使用命名空間取得所有元素,執行程式輸出XML檔案內容:
employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1M">
    <age>25</age>
    <name>PANKAJ</name>
    <role>Java Developer</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="2F">
    <age>34</age>
    <name>MONA</name>
    <role>Manager</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="3M">
    <age>45</age>
    <name>DAVE</name>
    <role>Support</role>
    <salary>1000</salary>
  </Employee></Employees>

以上就是Java&Xml教學(七)使用JDOM修改XML檔案內容的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
RSS文檔:Web聯合組織的基礎RSS文檔:Web聯合組織的基礎Apr 18, 2025 am 12:04 AM

RSS文檔是基於XML的結構化文件,用於發布和訂閱頻繁更新的內容。它的主要作用包括:1)自動化內容更新,2)內容聚合,3)提高瀏覽效率。通過RSSfeed,用戶可以訂閱並及時獲取來自不同來源的最新信息。

解碼RSS:內容提要的XML結構解碼RSS:內容提要的XML結構Apr 17, 2025 am 12:09 AM

RSS的XML結構包括:1.XML聲明和RSS版本,2.頻道(Channel),3.條目(Item)。這些部分構成了RSS文件的基礎,允許用戶通過解析XML數據來獲取和處理內容信息。

如何解析和利用基於XML的RSS提要如何解析和利用基於XML的RSS提要Apr 16, 2025 am 12:05 AM

RSSFEEDSUSEXMLTOSYNDICATECONTENT; PARSINGTHEMINVOLVESLOADINGINGINGINGINSSTRUCTURE,andExtractingData.ApplicationsIncludeBuildBuildingNewSagGregatorSaterNewSagGregatorSator andTrackingPodcastepodcastepisodes。

RSS文檔:他們如何提供您喜歡的內容RSS文檔:他們如何提供您喜歡的內容Apr 15, 2025 am 12:01 AM

RSS文檔的工作原理是通過XML文件發佈內容更新,用戶通過RSS閱讀器訂閱並接收通知。 1.內容髮布者創建並更新RSS文檔。 2.RSS閱讀器定期訪問並解析XML文件。 3.用戶瀏覽和閱讀更新內容。使用示例:訂閱TechCrunch的RSS源,只需複制鏈接到RSS閱讀器中即可。

用XML建造供稿:RSS的動手指南用XML建造供稿:RSS的動手指南Apr 14, 2025 am 12:17 AM

使用XML構建RSSfeed的步驟如下:1.創建根元素並設置版本;2.添加channel元素及其基本信息;3.添加條目(item)元素,包括標題、鏈接和描述;4.轉換XML結構為字符串並輸出。通過這些步驟,你可以從零開始創建一個有效的RSSfeed,並通過添加額外的元素如發布日期和作者信息來增強其功能。

創建RSS文檔:逐步教程創建RSS文檔:逐步教程Apr 13, 2025 am 12:10 AM

創建RSS文檔的步驟如下:1.使用XML格式編寫,根元素為,包含元素。 2.在內添加、、等元素描述頻道信息。 3.添加元素,每個代表一個內容條目,包含、、、等。 4.可選地添加和元素,豐富內容。 5.確保XML格式正確,使用在線工具驗證,優化性能並保持內容更新。

XML在RSS中的作用:聯合內容的基礎XML在RSS中的作用:聯合內容的基礎Apr 12, 2025 am 12:17 AM

XML在RSS中的核心作用是提供一種標準化和靈活的數據格式。 1.XML的結構和標記語言特性使其適合數據交換和存儲。 2.RSS利用XML創建標準化格式,方便內容共享。 3.XML在RSS中的應用包括定義feed內容的元素,如標題和發布日期。 4.優勢包括標準化和可擴展性,挑戰包括文件冗長和嚴格語法要求。 5.最佳實踐包括驗證XML有效性、保持簡潔、使用CDATA和定期更新。

從XML到可讀的內容:揭開RSS feed的神秘面紗從XML到可讀的內容:揭開RSS feed的神秘面紗Apr 11, 2025 am 12:03 AM

rssfeedsarexmldocuments usedforcontentAggregation and distribution.totransformthemintoreadableContent:1)parsethethexmlusinglibrarieslibrariesliblarieslikeparserinparserinpython.2)andledifferentifferentrssssssssssssssssssssssssssssssssssssssssssssssersions andpotentionparsingrorS.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。