0

我搜索了几个网站,它们都给出了如何写入 XML 文件的不同示例。这是我写入 XML 后的样子:

 <?xml version= "1.0"?>
  <Customers>
<Marker category="Production">
<title lang="en">Invensys</title>
<site_location>Neponset Avenue 22, Foxborough, Foxboro, MA, United States</site_location>
<latitude>42.066817</latitude>
<longitude>-71.24814</longitude>
<site_status>Normal</site_status>  
</Marker>
<Marker category="Production">
<title lang="en">Yokogawa Japan</title>
<site_location>Shinjuku, Tokyo, Japan</site_location>
<latitude>36.543915</latitude>
<longitude>136.629281</longitude>
<site_status>Critical</site_status>  
</Marker>
    </Customers>

我知道这有很多 API,所以请帮助我创建一个更简单的 XML 文件的基本编写方法,我将从那里继续。

提前致谢。

4

2 回答 2

2

Java 当然有用于编写 XML 的 API。从文档开始:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

Document doc = docBuilder.newDocument();

//Create the root Customers element
Element rootElement = doc.createElement("Customers");
doc.appendChild(rootElement);

//Create Marker element
Element markerElement = doc.createElement("Marker");
markerElement.setAttribute("category","Production");
rootElement.appendChild(markerElement);

等等。

一个不错的小教程可以在这里找到

这只是众多方法中的一种,但它可能是最好的入门方法。

于 2013-12-05T12:25:25.660 回答
0

好吧,这里有很多选择。您可以将 xml 写为字符串,然后将其输出到文件中,这就是快速肮脏的解决方案。您可以创建一个 DOM 对象,然后将它的字符串表示形式写入文本文件。您可以创建 JAXB 对象,并使用它们来创建字符串表示。

归根结底,无论您使用哪种方式,您所做的只是将文本写入以 .xml 结尾的文件

于 2013-12-05T12:22:30.163 回答