問題描述
我發現并遵循了 Stackoverflow (http://stackoverflow.com/questions/2310139/how-to-read-xml-response-from-a-url-in-java) 中關于如何讀取 XML 的示例來自 URL 的文件(如您在下面粘貼的代碼中所見).我唯一的麻煩是,既然我得到了讀取 XML 的程序,我該如何讓它來存儲它呢?例如,我可以讓它將信息保存到項目中內置的 XML 文件中嗎(如果可能的話,這對我來說是最好的解決方案)?例如,例如,我在項目中內置了一個空白 XML 文件.程序運行,從 URL 中讀取 XML 代碼,并將其全部存儲到預先構建的空白 XML 文件中.我可以這樣做嗎?
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));
}
}
推薦答案
很簡單:
File myOutput = new File("c:\myDirectory\myOutput.xml");
xform.transform(new DOMSource(doc), new StreamResult(myOutput));
這篇關于在線讀取 XML 并存儲它(使用 Java)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!