2017-02-04 50 views
1

我必须将映射的键/值序列化为XML文件,然后对其进行反序列化。UnknownHostException尝试读取XML文件

Map<String,Integer> map = new HashMap<>(); 
// ... 
LinkedList<Element> l = new LinkedList<Element>(); 
Element root = new Element("root"); 
for (String str : map.keySet()) { 
    l.add(new Element(str)); // key 
    l.getLast().appendChild(map.get(str).toString()); // value 
    root.appendChild(l.getLast()); 
} 
Document d = new Document(root); 

BufferedWriter out = new BufferedWriter(new FileWriter("data.xml")); 
out.write(d.toXML()); 
out.close(); 

d = new nu.xom.Builder().build("data.xml"); // ! 
Elements e = d.getRootElement().getChildElements(); 

但是,当我尝试读取XML文件,UnknownHostException被套上了标记线。

Exception in thread "main" java.net.UnknownHostException: file 

尽管XML文件已成功创建。格式化的版本看起来像:

<?xml version="1.0"?> 
<root> 
    <through>1</through> 
    <don>1</don> 
    <backed>1</backed> 
    <I>2</I> 
    <asList>1</asList> 
// .... 
</root> 

请问你能解释我有什么问题吗?

+0

你知道什么'建立()'正在为参数,其文件名,然后提供完整的文件路径。 –

+0

你应该关注[this](http://stackoverflow.com/help/someone-answers)。 –

回答

3

据@delephin,它能够更好地使用build(File in)版本build方法指向的文档,通过与您的data.xml到相关的File实例您build()方法,如下

d = new nu.xom.Builder().build(new File("data.xml")); 
+0

这样更好! :) –

+0

@AlastairMcCormack谢谢。 –

1

您需要正确的URL传递给build(),这包括本地文件。

可以使用获得本地文件的网址:

new File(path).toURI().toURL();