-
Notifications
You must be signed in to change notification settings - Fork 0
/
XMLCreator.java
84 lines (69 loc) · 2.4 KB
/
XMLCreator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package xml;
import java.io.*;
import java.util.*;
import java.text.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
public class XMLCreator {
static String idString = null;
static Document doc = null;
static String new_string = null;
public static void main(String[] args) {
}
//Takes an input and builds that input into XML format
public static String build(String inputfile, String contentId) {
try {
Scanner sc = new Scanner(new FileReader(inputfile));
String idString = contentId;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.newDocument();
Element rootElement = doc.createElement("feed");
doc.appendChild(rootElement);
Element first_entry = doc.createElement("entry");
rootElement.appendChild(first_entry);
Attr first_atr = doc.createAttribute("id");
Attr xmlLang = doc.createAttribute("xml:lang");
Attr xmlns = doc.createAttribute("xmlns");
first_atr.setValue(idString);
xmlLang.setValue("en-US");
xmlns.setValue("http://www.w3.org/2005/Atom");
rootElement.setAttributeNode(first_atr);
rootElement.setAttributeNode(xmlLang);
rootElement.setAttributeNode(xmlns);
Element current_entry = first_entry;
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals("entry")) {
Element entry = doc.createElement("entry");
rootElement.appendChild(entry);
current_entry = entry;
}
else {
String[] split = line.split(":");
Element entryElement = doc.createElement(split[0]);
entryElement.appendChild(doc.createTextNode(split[1]));
current_entry.appendChild(entryElement);
}
}
//Write to string
TransformerFactory tsf = TransformerFactory.newInstance();
Transformer ts = tsf.newTransformer();
DOMSource source = new DOMSource(doc);
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
ts.transform(source,result);
new_string = sw.toString();
ts.transform(source, result);
}
catch (IOException e) {
System.out.println("Broken or missing file.");
}
finally {
return new_string;
}
}
}