gpt4 book ai didi

java - 仅通过知道元素名称和他的父级生成 xml

转载 作者:数据小太阳 更新时间:2023-10-29 02:44:21 24 4
gpt4 key购买 nike

如题所述,我要生成一个xml文件。我需要的数据以 XML_NAMEXML_PARENT_NAME 的形式存储在数据库表中,它是 XML_NAME 的父级。

现在,你能给我一些想法,算法,如何只知道这两件事就生成我的 xml 文件吗?

提前致谢!

更新:XML 示例:

<root>
<element1></element1>
<element2></element2>
<element3>
<child>
<text></text>
</child>
</element3>
</root>

数据库模型:

XML_NAME | XML_PARENT_NAME
root
element1 root
element2 root
element3 root
child element3
text child

我只有这个数据库条目,我需要从这些条目构造一个 xml 文件,它看起来像上面的文件。

最佳答案

使用 XML 流编写器:

这是一个使用 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")));

关于java - 仅通过知道元素名称和他的父级生成 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35699926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com