我想生成一个xml文件,如标题中所述。我需要的数据以XML_NAME
和XML_PARENT_NAME
格式存储在数据库表格中,XML_NAME
是<root>
<element1></element1>
<element2></element2>
<element3>
<child>
<text></text>
</child>
</element3>
</root>
的父级。
现在,您能否通过了解这两件事情,给我一些想法,算法,如何生成我的xml文件?
提前致谢!
更新: XML示例:
XML_NAME | XML_PARENT_NAME
root
element1 root
element2 root
element3 root
child element3
text child
数据库模型:
@RepositoryRestController
public class PersonOmnisearchController {
@Autowired
private PersonRepository personRepository;
@ResponseBody
@RequestMapping(value = "/persons/search/personOmnisearch", method = RequestMethod.GET)
public ResponseEntity<?> personOmnisearch(@RequestParam("search") String search, PersistentEntityResourceAssembler assembler) {
Person p = personRepository.findOne(Long.valueOf(search));
if (p == null) {
p = personRepository.findBySsn(search);
}
if (p == null) {
throw new ResourceNotFoundException();
}
return ResponseEntity.ok(assembler.toResource(p));
}
}
我只有这些数据库条目,从这些数据库中我需要构建一个xml文件,它就像上面那样。
答案 0 :(得分:0)
这是一个易于实现的算法,假设您从数据库中检索到一个简单的结果集,其中包含您提到的两个列。
答案 1 :(得分:0)
使用XML Stream writer:
这是一个使用FileWriter将一系列事件写入磁盘的简单示例:
XMLOutputFactory factory = XMLOutputFactory.newInstance();
try {
XMLStreamWriter writer = factory.createXMLStreamWriter(
new FileWriter("data\\output2.xml"));
writer.writeStartDocument();
writer.writeStartElement("document");
writer.writeStartElement("data");
writer.writeAttribute("name", "value");
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
执行此代码的结果是以下XML文件:
<?xml version='1.0' encoding='utf-8'?>
<document><data name="value"></data> </document>
价:http://tutorials.jenkov.com/java-xml/stax-xmlstreamwriter.html
如果您不需要值,只需使用writeStartElement和writeEndElement
子元素的另一个选项是:
Element root=new Element("CONFIGURATION");
Document doc=new Document();
Element child1=new Element("BROWSER");
child1.addContent("chrome");
Element child2=new Element("BASE");
child1.addContent("http:fut");
Element child3=new Element("EMPLOYEE");
child3.addContent(new Element("EMP_NAME").addContent("Anhorn, Irene"));
root.addContent(child1);
root.addContent(child2);
root.addContent(child3);
doc.setRootElement(root);
XMLOutputter outter=new XMLOutputter();
outter.setFormat(Format.getPrettyFormat());
outter.output(doc, new FileWriter(new File("myxml.xml")));
答案 2 :(得分:0)
您可以使用@mlkammer建议的算法。
收集包含所有信息的最终地图后,您可以将其写入文件。
例如,您的地图显示为Map<String, List<String>> map
。
之后,您可以轻松地格式化并将其写入文件。
以下是 代码段 :
import org.w3c.dom.*;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class XmlBuilder {
private DocumentBuilder builder;
private Document doc;
/**
* Constructs an item list builder.
*
* @throws CreateDocumentConfigurationException
*/
public XmlBuilder() throws CreateDocumentConfigurationException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new CreateDocumentConfigurationException("exception create new document", e);
}
}
/**
* Builds a DOM document for an array list of items.
*
* @param elementMap map of items.
* @return a DOM document describing the items.
*/
public Document build(Map<String, List<String>> elementMap) {
doc = builder.newDocument();
doc.appendChild(createItems(elementMap));
return doc;
}
/**
* Builds a DOM element for an array list of items.
*
* @param elementMap the map of items
* @return a DOM element describing the items
*/
private Element createItems(Map<String, List<String>> elementMap) {
Element e = null;
for (Map.Entry<String, List<String>> anItem : elementMap.entrySet()) {
e = doc.createElement(anItem.getKey());
for (Node node : createItemsList(anItem.getValue())) {
e.appendChild(node);
}
}
return e;
}
private List<Node> createItemsList(List<String> items) {
List<Node> result = new ArrayList<>();
for (String item : items) {
Element item1 = createItem(item);
result.add(item1);
}
return result;
}
/**
* Builds a DOM element for an item.
*
* @param anItem the item
* @return a DOM element describing the item
*/
private Element createItem(String anItem) {
// if you need some text element to your element - just append it here.
return doc.createElement(anItem);
}
/**
* Builds the text content for document
*
* @param name element
* @param text content
* @return text element
*/
private Element createTextElement(String name, String text) {
Text t = doc.createTextNode(text);
Element e = doc.createElement(name);
e.appendChild(t);
return e;
}
private String generateXmlContent(Map<String, List<String>> elementMap) {
String content;
Document doc = build(elementMap);
DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
LSSerializer ser = implLS.createLSSerializer();
ser.getDomConfig().setParameter("format-pretty-print", true);
content = ser.writeToString(doc);
return content;
}
public void writeToXmlFile(String xmlContent) {
File theDir = new File("./output");
if (!theDir.exists())
theDir.mkdir();
String fileName = "./output/" + this.getClass().getSimpleName() + "_"
+ Calendar.getInstance().getTimeInMillis() + ".xml";
try (OutputStream stream = new FileOutputStream(new File(fileName))) {
try (OutputStreamWriter out = new OutputStreamWriter(stream, StandardCharsets.UTF_16)) {
out.write(xmlContent);
out.write("\n");
}
} catch (IOException ex) {
System.err.println("Cannot write to file!" + ex.getMessage());
}
}
public static void main(String[] args) throws CreateDocumentConfigurationException {
XmlBuilder xmlBuilder = new XmlBuilder();
Map<String, List<String>> map = MapFactory.mapOf(MapFactory.entry("root", Arrays.asList("element1", "element2", "element3")));
String xmlContent = xmlBuilder.generateXmlContent(map);
xmlBuilder.writeToXmlFile(xmlContent);
}
}
执行后的输出 将是:
<?xml version="1.0" encoding="UTF-16"?>
<root>
<element1/>
<element2/>
<element3/>
</root>