java 中有关xml操作速记

java 中有关xml操作速记

创建Document对象 :

 

将字符串转换为Document对象:

 

  1. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  2.  factory.setValidating(false);
  3.  factory.setNamespaceAware(true);
  4.  Document dom = factory.newDocumentBuilder().parse(new InputSource(new StringReader(queryDef)));

 

得到字符串形式的Document对象:

  1. StringWriter mysw = new StringWriter();
  2.  
  3.  Transformer trans = TransformerFactory.newInstance().newTransformer();
  4.  doc.normalize();
  5.  trans.transform(new DOMSource(doc),new StreamResult(mysw));
  6.  
  7.  String docXmlmySw.toString();

得到字符串形式的Node对象:

 

  1. TransformerFactory tf = TransformerFactory.newInstance();
  2.  Transformer transformer = tf.newTransformer();
  3.  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8");
  4.  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  5.  
  6.  DOMSource source = new DOMSource(node);
  7.  StringWriter writer = new StringWriter();
  8.  StreamResult sResult = new StreamResult(writer);
  9.  transformer.transform(source, sResult);
  10.  String result = writer.toString();

 

 另: 如果一个Document结点需要悬挂(append)来自另一个Document对象的结点对象,直接用appendChild方法会出现org.w3c.dom.DOMException: DOM005 Wrong document error happens错误,解决办法是: oneNode.appendChild(oneDoc.importNode(otherNode,true)); 请注意其中importNode方法的使用.

以上所有关于xml操作均有可能出现非预期异常,所以需要捕获并作相关处理.

Tags: java  xml
 

 

  1. Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值