java 中有关xml操作速记
Author:lyore Date:2007-03-05 12:57
创建Document对象 :
将字符串转换为Document对象:
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setValidating(false);
- factory.setNamespaceAware(true);
- Document dom = factory.newDocumentBuilder().parse(new InputSource(new StringReader(queryDef)));
得到字符串形式的Document对象:
- StringWriter mysw = new StringWriter();
- Transformer trans = TransformerFactory.newInstance().newTransformer();
- doc.normalize();
- trans.transform(new DOMSource(doc),new StreamResult(mysw));
- String docXml = mySw.toString();
得到字符串形式的Node对象:
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8");
- transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- DOMSource source = new DOMSource(node);
- StringWriter writer = new StringWriter();
- StreamResult sResult = new StreamResult(writer);
- transformer.transform(source, sResult);
- 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操作均有可能出现非预期异常,所以需要捕获并作相关处理.
- Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();