XML的DOM编程

package jp.go.ssid.sss.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class SssCommon {


 public SssCommon() {
 }

 /** SssCommon实例 */
 private static SssCommon sssCommon = null;

 /** XML Document */
 private Document doc = null;

 /** 機能名:XML解析 */
 private final String KINOU_NM_SSSCOMMON = "XML解析";

 /**
  * コンストラクタ。
  * @param stream ストリーム
  * @param validate 検証の有無
  */
 private SssCommon(ByteArrayInputStream stream, boolean validate) throws Exception {

  try {
   // DOMパーサ用ファクトリの生成
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

   // 検証
   factory.setValidating(validate);

   // DOM Documentインスタンス用ファクトリの生成
   DocumentBuilder builder = factory.newDocumentBuilder();

   // 解析とDocumentインスタンスの取得
   doc = builder.parse(stream, SssPropertyReader.getProperty(SssNames.PROP_BASE_URI));

  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
   SssLogSender.error(e, KINOU_NM_SSSCOMMON, SssMessage.SSS_DETAIL_ERR_MSG_001, this.getClass());
   throw e;
  }

 }

 /**
  * コンストラクタ。
  * @param filepath ファイルパス
  */
 private SssCommon(String filepath) throws Exception {

  try {
   // DOMパーサ用ファクトリの生成
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

   // 検証
   factory.setValidating(true);

   // DOM Documentインスタンス用ファクトリの生成
   DocumentBuilder builder = factory.newDocumentBuilder();

   // 解析とDocumentインスタンスの取得
   doc = builder.parse(filepath);

  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
     throw e;
  }

 }

 /**
  * SssCommon インスタンスの生成
  * @param stream ストリーム
  * @return SssCommonのインスタンス
  */
 public static SssCommon getInstance(ByteArrayInputStream stream) throws Exception {

  return getInstance(stream, true);
 }

 /**
  * SssCommonのインスタンスの生成
  * @param stream ストリーム
  * @param validate 検証の有無
  * @return SssCommonのインスタンス
  */
 public static SssCommon getInstance(ByteArrayInputStream stream, boolean validate) throws Exception {

  sssCommon = new SssCommon(stream, validate);
  return sssCommon;
 }

 /**
  * SssCommonのインスタンスの生成
  * @param filepath ファイルパス
  * @return SssCommonのインスタンス
  */
 public static SssCommon getInstance(String filepath) throws Exception {

  sssCommon = new SssCommon(filepath);
  return sssCommon;
 }

 /**
  * 引数で指定されたパスに存在する最初のノード値を返します。 
  *
  * @param path ロケーションパス
  * @return 指定ノードの値
  *
  */
 public String getNodeValue(String path) throws Exception {

  try {
   // Nodeの取得
   Node node = XPathAPI.selectSingleNode(doc, path);
   if (node == null) {
    throw new NullPointerException("PATH = " + path);
   }
   Node child = node.getFirstChild();
   if (child == null) {
    return "";
   }
   return (child.getNodeValue()).trim();
  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
     throw e;
  }
 }

 /**
  * 引数で指定されたパスに存在する最初のノードに値を設定します。
  *
  * @param path ロケーションパス
  * @param value 設定する値
  */
 public void setNodeValue(String path, String value) throws Exception {

  try {
   // Nodeの取得
   Node node = XPathAPI.selectSingleNode(doc, path);
   if (node == null) {
    throw new NullPointerException("PATH = " + path);
   }
   Node child = node.getFirstChild();
   if (child == null) {
    node.appendChild(doc.createTextNode(value));
   } else {
    child.setNodeValue(value);
   }
  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
    throw e;
  }
 }

 /**
  * 引数で指定されたパスに存在するノードの数を返します。
  * @param path ロケーションパス
  * @return  ノードの数
  */
 public int getNodeListSize(String path) throws Exception {

  try {
   // NodeListの取得
   NodeList list = XPathAPI.selectNodeList(doc, path);
   if (list == null) {
    return 0;
   } else {
    return list.getLength();
   }
  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
      throw e;
  }
 }

 /**
  * ノードを削除する。
  * @param path ロケーションパス
  */
 public void removeNodes(String path) throws Exception {

  try {
   Node node = XPathAPI.selectSingleNode(doc, path);
   if (node == null) {
    throw new NullPointerException("PATH = " + path);
   }
   Node parent = node.getParentNode();
   NodeList nodeList = XPathAPI.selectNodeList(doc, path);
   if ((parent != null) && (nodeList != null)) {
    for (int i = 0; i < nodeList.getLength(); i++) {
     Node child = XPathAPI.selectSingleNode(doc, path);
     if (child != null) {
      parent.removeChild(child);
     }
    }
   }
  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
   throw e;
  }
 }

 /**
  * 指定したノードに新しい子ノードを追加する。
  * @param path ロケーションパス
  * @param childnode 追加する子ノード
  */
 public void appendChildNode(String path, String childnode) throws Exception {
  try {

   Node node = XPathAPI.selectSingleNode(doc, path);
   if (node == null) {
    throw new NullPointerException("PATH = " + path);
   }
   Element element = doc.createElement(childnode);
   node.appendChild(element);

  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
      throw e;
  }
 }

 /**
  * 指定したノードに新しいノードとテキストノードを追加する。
  * @param path ロケーションパス
  * @param childnode 追加する子ノード
  * @param value 追加するテキストノード
  */
 public void appendChildNode(String path, String childnode, String value) throws Exception {
  try {

   Node node = XPathAPI.selectSingleNode(doc, path);
   if (node == null) {
    throw new NullPointerException("PATH = " + path);
   }
   Element element = doc.createElement(childnode);
   element.appendChild(doc.createTextNode(value));
   node.appendChild(element);

  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
  throw e;
  }
 }

 /**
  * XMLデータを文字列で返します。
  * @return  XMLデータの文字列
  */
 public String getDocument() throws Exception {

  try {

   TransformerFactory transFactory = TransformerFactory.newInstance();
   Transformer transformer = transFactory.newTransformer();
   if (doc.getDoctype() != null && doc.getDoctype().getSystemId() != null) {
    transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
   }
   DOMSource source = new DOMSource(doc);
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   StreamResult result = new StreamResult(out);
   transformer.transform(source, result);
   return out.toString("utf-8");

  } catch (Exception e) {
   //XMLの解析でエラーが発生したことをログに出力する
      throw e;
  }
 }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值