문제

I have searched several websites and all of them give different examples of how to write to a XML file. This is how the XML should look like after I write into it:

 <?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>

I know there are many API's for this so please help me with a basic writing method for a creation of a simpler XML file and I will continue from there.

Thanks in advance.

도움이 되었습니까?

해결책

Java certainly has APIs for writing XML. Start with a Document:

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);

and so on.

A nice little tutorial can be found here

This is just one way of many, but it's probably the best one to get started with.

다른 팁

Well, there's a whole host of options here. you could write the xml as a string, then just output it to a file, thats the quick dirty solution. You could create a DOM object and then write the string representation of it into a text file. You could create JAXB objects, and use them to create the string representation.

At the end of the day, whichever you use, all you're doing is writing text to a file that ends in .xml

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top