開発者ドキュメント

JavaでXMLファイルを変更する方法 – (JDOM Parser)

1. XMLファイル

XMLファイルの前後を参照してください。


File:file.xml

– 元のXMLファイル。

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="1">
    <firstname>yong</firstname>
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>5000</salary>
  </staff>
</company>

その後、JDOM XML Parserを使用してXMLファイルを更新します。

  1. スタッフの下に新しい「年齢」要素を追加する

  2. スタッフ属性を更新するid = 2

  3. 給与額を7000に更新する

  4. スタッフの下の「firstname」要素を削除する


File:file.xml

– 新しく変更されたXMLファイル。

<?xml version="1.0" encoding="UTF-8"?>
<company>
  <staff id="2">
    <lastname>mook kim</lastname>
    <nickname>mkyong</nickname>
    <salary>7000</salary>
    <age>28</age>
  </staff>
</company>

2. JDOMの例

既存のXMLファイルを更新または変更するためのJDOMパーサー。

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class ModifyXMLFile {
    public static void main(String[]args) {

      try {

        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("c:\\file.xml");

        Document doc = (Document) builder.build(xmlFile);
        Element rootNode = doc.getRootElement();

       //update staff id attribute
        Element staff = rootNode.getChild("staff");
        staff.getAttribute("id").setValue("2");

       //add new age element
        Element age = new Element("age").setText("28");
        staff.addContent(age);

       //update salary value
        staff.getChild("salary").setText("7000");

       //remove firstname element
        staff.removeChild("firstname");

        XMLOutputter xmlOutput = new XMLOutputter();

       //display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, new FileWriter("c:\\file.xml"));

       //xmlOutput.output(doc, System.out);

        System.out.println("File updated!");
      } catch (IOException io) {
        io.printStackTrace();
      } catch (JDOMException e) {
        e.printStackTrace();
      }
    }
}

リンク://タグ/java/[java]リンク://タグ/jdom/[jdom]リンク://タグ/xml/[xml]

モバイルバージョンを終了