Java&Xmlチュートリアル (7) 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. 性別が男性の場合は 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'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'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) を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

PHPは、サーバー側で広く使用されているスクリプト言語で、特にWeb開発に適しています。 1.PHPは、HTMLを埋め込み、HTTP要求と応答を処理し、さまざまなデータベースをサポートできます。 2.PHPは、ダイナミックWebコンテンツ、プロセスフォームデータ、アクセスデータベースなどを生成するために使用され、強力なコミュニティサポートとオープンソースリソースを備えています。 3。PHPは解釈された言語であり、実行プロセスには語彙分析、文法分析、編集、実行が含まれます。 4.PHPは、ユーザー登録システムなどの高度なアプリケーションについてMySQLと組み合わせることができます。 5。PHPをデバッグするときは、error_reporting()やvar_dump()などの関数を使用できます。 6. PHPコードを最適化して、キャッシュメカニズムを使用し、データベースクエリを最適化し、組み込み関数を使用します。 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHPは、シンプルな構文と高い実行効率を備えたWeb開発に適しています。 2。Pythonは、簡潔な構文とリッチライブラリを備えたデータサイエンスと機械学習に適しています。

カプセルは3次元の幾何学的図形で、両端にシリンダーと半球で構成されています。カプセルの体積は、シリンダーの体積と両端に半球の体積を追加することで計算できます。このチュートリアルでは、さまざまな方法を使用して、Javaの特定のカプセルの体積を計算する方法について説明します。 カプセルボリュームフォーミュラ カプセルボリュームの式は次のとおりです。 カプセル体積=円筒形の体積2つの半球体積 で、 R:半球の半径。 H:シリンダーの高さ(半球を除く)。 例1 入力 RADIUS = 5ユニット 高さ= 10単位 出力 ボリューム= 1570.8立方ユニット 説明する 式を使用してボリュームを計算します。 ボリューム=π×R2×H(4

PHPとPythonにはそれぞれ独自の利点があり、さまざまなシナリオに適しています。 1.PHPはWeb開発に適しており、組み込みのWebサーバーとRich Functionライブラリを提供します。 2。Pythonは、簡潔な構文と強力な標準ライブラリを備えたデータサイエンスと機械学習に適しています。選択するときは、プロジェクトの要件に基づいて決定する必要があります。

PHPは、特に迅速な開発や動的なコンテンツの処理に適していますが、データサイエンスとエンタープライズレベルのアプリケーションには良くありません。 Pythonと比較して、PHPはWeb開発においてより多くの利点がありますが、データサイエンスの分野ではPythonほど良くありません。 Javaと比較して、PHPはエンタープライズレベルのアプリケーションでより悪化しますが、Web開発により柔軟性があります。 JavaScriptと比較して、PHPはバックエンド開発により簡潔ですが、フロントエンド開発のJavaScriptほど良くありません。

Java は、初心者と経験豊富な開発者の両方が学習できる人気のあるプログラミング言語です。このチュートリアルは基本的な概念から始まり、高度なトピックに進みます。 Java Development Kit をインストールしたら、簡単な「Hello, World!」プログラムを作成してプログラミングを練習できます。コードを理解したら、コマンド プロンプトを使用してプログラムをコンパイルして実行すると、コンソールに「Hello, World!」と出力されます。 Java の学習はプログラミングの旅の始まりであり、習熟が深まるにつれて、より複雑なアプリケーションを作成できるようになります。
