java xml存储,在线阅读XML并存储它(使用Java)

I found and followed an example from Stackoverflow (http://stackoverflow.com/questions/2310139/how-to-read-xml-response-from-a-url-in-java) of how to read an XML file from a URL (as you can see in my code pasted below). My only trouble is that now that I got the program to read the XML, how do I get it to store it? For example, could I make it save the information to a XML file built into the project (this would be the best solution for me, if it's possible)? Such as, take for example, I have a blank XML file built into the project. The program runs, reads the XML code off of the URL, and stores it all into the pre-built blank XML file. Could I do this?

If I sound confusing or un-clear about anything, just ask me to clarify what I'm looking for.

And here is my code, if you'd like to look at what I have so far:

package xml.parsing.example;

import java.io.IOException;

import java.net.URL;

import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;

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 XmlParser {

public static void main (String[] args) throws IOException, ParserConfigurationException, SAXException, TransformerException {

URL url = new URL("http://totheriver.com/learn/xml/code/employees.xml");

URLConnection conn = url.openConnection();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(conn.getInputStream());

TransformerFactory tfactory = TransformerFactory.newInstance();

Transformer xform = tfactory.newTransformer();

// that’s the default xform; use a stylesheet to get a real one

xform.transform(new DOMSource(doc), new StreamResult(System.out));

}

}

解决方案

Very simply:

File myOutput = new File("c:\\myDirectory\\myOutput.xml");

xform.transform(new DOMSource(doc), new StreamResult(myOutput));

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值