ホームページ  >  記事  >  バックエンド開発  >  Java&Xmlチュートリアル (7) JDOMを使用してXMLファイルの内容を変更する

Java&Xmlチュートリアル (7) JDOMを使用してXMLファイルの内容を変更する

黄舟
黄舟オリジナル
2017-02-22 14:51:351844ブラウズ

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. 性別が男性の場合は id 属性値の後に M を追加し、性別が女性の場合は id 属性値の後に F を追加します。
3. 性別要素を削除します。
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. 性別が男性の場合は id 属性値の後に M を追加し、性別が女性の場合は id 属性値の後に F を追加します。
3. 性別要素を削除します。
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 チュートリアル (7) JDOM を使用した変更 XML ファイルの内容については、PHP 中国語 Web サイト (www.php.cn) を参照してください。


声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。