Dom to String(将xml文件转化为String)
www.diybl.com 时间 : 2008-05-03 作者:佚名 编辑:本站 点击: 2103 [ 评论 ]
-
-
1.links.mxl文件内容如下:
<?xml version="1.0" encoding="utf-8"?>
<links>
<link>
<text>一维可航</text>
<url newWindow="no">CSDN--一维可航的Blog</url>
<author>一维可航</author>
<date>
<day>2</day>
<month>1</month>
<year>2001</year>
</date>
<description>北京海淀.</description>
</link>
</links>
2.GetXml.java源码:
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.w3c.dom.Document;
import org.xml.sax.SAXException;
public class GetXml
{
/**
* @param args
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) {
try
{
String myxmlString = "";
myxmlString = getString("sunxun");
System.out.println(myxmlString);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SAXException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getString(String name) throws IOException, SAXException
{
// 根据传过来的参数进行判断并解析XML TO String
String xmlString = "";
if (name != null & name.equalsIgnoreCase("sunxun"))
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try
{
db = dbf.newDocumentBuilder();
}
catch (ParserConfigurationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = db.parse("links.xml");
xmlString = toString(doc);
}
return xmlString;
}
static public String toString(Document document)
{
String result = null;
if (document != null)
{
StringWriter strWtr = new StringWriter();
StreamResult strResult = new StreamResult(strWtr);
TransformerFactory tfac = TransformerFactory.newInstance();
try
{
Transformer t = tfac.newTransformer();
t.setOutputProperty(OutputKeys.ENCODING, "gb2312");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,// text
t.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "4");
t.transform(new DOMSource(document.getDocumentElement()),
strResult);
}
catch (Exception e)
{
System.err.println("XML.toString(Document): " + e);
}
result = strResult.getWriter().toString();
}
return result;
}
}
文章出处:飞诺网(www.diybl.com):http://www.diybl.com/course/3_program/java/javajs/200853/112271.html