JavaのDocumentクラスの使用法とは?

DocumentクラスはXMLドキュメントのルートノードを表す、org.w3c.domパッケージ内のインターフェースです。XMLドキュメントを操作するためのメソッドとプロパティを定義します。

Documentクラスの使い方は次のとおりです。

  1. XMLドキュメントの作成: DocumentBuilderクラスのparse()メソッドを使用してファイル、入力ストリーム、文字列からXMLドキュメントを解析し、Document オブジェクトを返します。

ネイティブで日本語に書き換えた例文のみ必要です。選択肢は1つだけで結構です。

File xmlFile = new File("path/to/xml/file.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
  1. DocumentオブジェクトのcreateElement()メソッドを使用して新しいXML要素を作成し、appendChild()メソッドを使用してそれをドキュメントに追加することができます。

そのコードの例を示してください。

Element rootElement = document.createElement("root");
document.appendChild(rootElement);

Element childElement = document.createElement("child");
rootElement.appendChild(childElement);
  1. XMLエレメントを取得するには、DocumentオブジェクトのgetElementsByTagName()メソッドで指定されたタグ名を持つすべてのエレメントを取得したり、getElementById()メソッドで指定されたIDのエレメントを取得します。

サンプルコード:

NodeList nodeList = document.getElementsByTagName("elementName");
Element element = (Element) nodeList.item(0);

Element elementById = document.getElementById("elementId");
  1. XML 要素の編集: `Element` オブジェクトの `setAttribute()` メソッドを使用して要素の属性値を設定し、 `setTextContent()` メソッドを使用して要素のテキスト内容を設定します。

サンプルコード:

element.setAttribute("attributeName", "attributeValue");
element.setTextContent("text content");
  1. DocumentオブジェクトをXML文字列に変換し、ファイルまたは出力ストリームへ保存することができます。

サンプルコード

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("path/to/output.xml"));
transformer.transform(source, result);

Documentクラスを使えば、XML文書の作成、操作、保存が簡単にできます。

bannerAds