検索
ホームページバックエンド開発XML/RSS チュートリアルJava&Xmlチュートリアル (3) DOMを使用してXMLファイルの内容を変更する

DOM 解析メソッドは、要素の追加、要素の削除、要素の値の変更、要素の属性の変更などの操作を完了するために使用することもできます。

XML ファイルには次の内容があります:
employee.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
    <Employee id="1">
        <name>Pankaj</name>
        <age>29</age>
        <role>Java Developer</role>
        <gender>Male</gender>
    </Employee>
    <Employee id="2">
        <name>Lisa</name>
        <age>35</age>
        <role>CSS Developer</role>
        <gender>Female</gender>
    </Employee></Employees>

XML ファイルの内容を変更します:
1. 従業員の性別 (性別) に応じて「id」属性値を変更します。 id 属性値に「」を追加し、 Female の id 属性値に「F」を追加します。
2. name 要素の値をすべて大文字に変更します。
3. 「性別」要素はもう意味がないので、削除します。
4. 従業員ノードの下に「給与」ノードを追加します。
上記の操作が完了したら、コンテンツを新しい XML ファイルに保存します。
以下は DOM 解析を使用する Java プログラム コードです:
ModifyXMLDOM.java

package com.journaldev.xml;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;import org.w3c.dom.Element;
import org.w3c.dom.Node;import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;public class ModifyXMLDOM {

    public static void main(String[] args) {
        String filePath = "employee.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();

            //update attribute value
            updateAttributeValue(doc);

            //update Element value
            updateElementValue(doc);

            //delete element
            deleteElement(doc);

            //add new element
            addElement(doc);

            //write the updated document to file or console
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("employee_updated.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");

        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }

    private static void addElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;

        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Element salaryElement = doc.createElement("salary");
            salaryElement.appendChild(doc.createTextNode("10000"));
            emp.appendChild(salaryElement);
        }
    }

    private static void deleteElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node genderNode = emp.getElementsByTagName("gender").item(0);
            emp.removeChild(genderNode);
        }

    }

    private static void updateElementValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
            name.setNodeValue(name.getNodeValue().toUpperCase());
        }
    }

    private static void updateAttributeValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
            if(gender.equalsIgnoreCase("male")){
                //prefix id attribute with M
                emp.setAttribute("id", "M"+emp.getAttribute("id"));
            }else{
                //prefix id attribute with F
                emp.setAttribute("id", "F"+emp.getAttribute("id"));
            }
        }
    }

}

出力 XML ファイルの内容:
employee_updated.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
    <Employee id="M1">
        <name>PANKAJ</name>
        <age>29</age>
        <role>Java Developer</role>

    <salary>10000</salary></Employee>
    <Employee id="F2">
        <name>LISA</name>
        <age>35</age>
        <role>CSS Developer</role>

    <salary>10000</salary></Employee></Employees>

元のアドレス: http://www.php.cn/

DOM 解析メソッドXML データの変更にも使用でき、要素の追加、要素の削除、要素の値の変更、要素の属性の変更などの操作を完了できます。
XML ファイルには次の内容があります:
employee.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
    <Employee id="1">
        <name>Pankaj</name>
        <age>29</age>
        <role>Java Developer</role>
        <gender>Male</gender>
    </Employee>
    <Employee id="2">
        <name>Lisa</name>
        <age>35</age>
        <role>CSS Developer</role>
        <gender>Female</gender>
    </Employee></Employees>

XML ファイルの内容を変更します:
1. 従業員の性別 (性別) に従って「id」属性値を変更します。男性( Male )の id 属性の値に「M」を追加し、女性の id 属性の値に「F」を追加します。
2. name 要素の値をすべて大文字に変更します。
3. 「性別」要素はもう意味がないので、削除します。
4. 従業員ノードの下に「給与」ノードを追加します。
上記の操作が完了したら、コンテンツを新しい XML ファイルに保存します。
以下は DOM メソッドを使用して解析された Java プログラム コードです:
ModifyXMLDOM.java

package com.journaldev.xml;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;import org.w3c.dom.Element;
import org.w3c.dom.Node;import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;public class ModifyXMLDOM {

    public static void main(String[] args) {
        String filePath = "employee.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();

            //update attribute value
            updateAttributeValue(doc);

            //update Element value
            updateElementValue(doc);

            //delete element
            deleteElement(doc);

            //add new element
            addElement(doc);

            //write the updated document to file or console
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("employee_updated.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");

        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }

    private static void addElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;

        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Element salaryElement = doc.createElement("salary");
            salaryElement.appendChild(doc.createTextNode("10000"));
            emp.appendChild(salaryElement);
        }
    }

    private static void deleteElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node genderNode = emp.getElementsByTagName("gender").item(0);
            emp.removeChild(genderNode);
        }

    }

    private static void updateElementValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Node name = emp.getElementsByTagName("name").item(0).getFirstChild();
            name.setNodeValue(name.getNodeValue().toUpperCase());
        }
    }

    private static void updateAttributeValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;
        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            String gender = emp.getElementsByTagName("gender").item(0).getFirstChild().getNodeValue();
            if(gender.equalsIgnoreCase("male")){
                //prefix id attribute with M
                emp.setAttribute("id", "M"+emp.getAttribute("id"));
            }else{
                //prefix id attribute with F
                emp.setAttribute("id", "F"+emp.getAttribute("id"));
            }
        }
    }

}

出力される XML ファイルの内容:
employee_updated.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><Employees>
    <Employee id="M1">
        <name>PANKAJ</name>
        <age>29</age>
        <role>Java Developer</role>

    <salary>10000</salary></Employee>
    <Employee id="F2">
        <name>LISA</name>
        <age>35</age>
        <role>CSS Developer</role>

    <salary>10000</salary></Employee></Employees>

上記は Java&Xml チュートリアル (3) DOM メソッドを使用して内容を変更する内容ですXML ファイルの詳細 関連コンテンツについては、PHP 中国語 Web サイト (www.php.cn) にご注意ください。


声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
RSSにおけるXMLの利点:技術的なディープダイビングRSSにおけるXMLの利点:技術的なディープダイビングApr 23, 2025 am 12:02 AM

XMLには、RSSの構造化データ、スケーラビリティ、クロスプラットフォームの互換性、解析検証の利点があります。 1)構造化されたデータにより、コンテンツの一貫性と信頼性が保証されます。 2)スケーラビリティにより、コンテンツのニーズに合わせてカスタムタグを追加できます。 3)クロスプラットフォームの互換性により、さまざまなデバイスでシームレスに動作します。 4)分析および検証ツールは、フィードの品質と完全性を確保します。

XMLのRSS:コンテンツシンジケーションのコアを発表しますXMLのRSS:コンテンツシンジケーションのコアを発表しますApr 22, 2025 am 12:08 AM

XMLでのRSSの実装は、構造化されたXML形式を使用してコンテンツを整理することです。 1)RSSは、チャネル情報やプロジェクトリストなどの要素を含むデータ交換形式としてXMLを使用します。 2)RSSファイルを生成する場合、コンテンツは仕様に従って整理し、サブスクリプションのためにサーバーに公開する必要があります。 3)RSSファイルは、読者またはプラグインを介してサブスクライブして、コンテンツを自動的に更新できます。

基本を超えて:高度なRSSドキュメント機能基本を超えて:高度なRSSドキュメント機能Apr 21, 2025 am 12:03 AM

RSSの高度な機能には、コンテンツネームスペース、拡張モジュール、条件付きサブスクリプションが含まれます。 1)コンテンツネームスペースはRSS機能を拡張します。2)dublincoreやiTunesなどの拡張モジュールを拡張してメタデータを追加します。これらの関数は、情報収集の効率を改善するためにXML要素と属性を追加することにより実装されます。

XMLバックボーン:RSSフィードが構造化される方法XMLバックボーン:RSSフィードが構造化される方法Apr 20, 2025 am 12:02 AM

rssfeedsusexmltoStructurecontentupdates.1)xmlprovidesahierararchStructurefordata.2)theelementDefinesthefeed'sidentityandContainesements.3)letentionEntentividualContentPieces.4)

RSS&XML:Webコンテンツのダイナミックデュオを理解するRSS&XML:Webコンテンツのダイナミックデュオを理解するApr 19, 2025 am 12:03 AM

RSSとXMLは、Webコンテンツ管理のためのツールです。 RSSはコンテンツの公開と購読に使用され、XMLはデータの保存と転送に使用されます。コンテンツの公開、サブスクリプション、および更新プッシュで動作します。使用法の例には、RSS公開ブログ投稿やXML保存本情報が含まれます。

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。チャネル(チャネル)、3。アイテムが含まれます。これらの部品はRSSファイルの基礎を形成し、XMLデータを解析することにより、ユーザーがコンテンツ情報を取得および処理できるようにします。

XMLベースのRSSフィードを解析して利用する方法XMLベースのRSSフィードを解析して利用する方法Apr 16, 2025 am 12:05 AM

rssfeedsusexmltosyndicatecontent; parsingtheminvolvesloadingxml、navigating structure、and extractingdata.applicationsincludebuildingnewsaggretationsandtrackingpodcastepisodes。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

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

ホットツール

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン