通过只知道元素名称和他的父元素来生成xml

时间:2016-02-29 12:44:48

标签: java xml

我想生成一个xml文件,如标题中所述。我需要的数据以XML_NAMEXML_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文件,它就像上面那样。

3 个答案:

答案 0 :(得分:0)

这是一个易于实现的算法,假设您从数据库中检索到一个简单的结果集,其中包含您提到的两个列。

  1. 首先遍历所有记录,并为每个XML_NAME名称构建XML Node对象(将XML Node对象放入List中)。
  2. 使用String键(XML_NAME名称)和XML Node对象作为值创建HashMap。将每个XML节点添加为此映射中的条目。
  3. 再次遍历所有记录(仅一次),对于每个XML_NAME - XML_PARENT_NAME对,在地图中查找两个XML Node对象。将前者的XML节点添加到后者的子节点列表中。
  4. 创建根XML节点。循环遍历XML节点列表,并将每个没有父节点的节点添加到根节点,作为根节点的子节点。
  5. 将根XML节点转换为String或随意执行任何操作。

答案 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>