gpt4 book ai didi

java - 使用 apache axiom 生成示例 xml 文件

转载 作者:行者123 更新时间:2023-11-30 08:26:13 24 4
gpt4 key购买 nike

请帮助使用 apache axiom 生成 xml 文件,任何带有一个父标签和两个子标签的 xml 文件,我尝试了以下代码

OMFactory factory = OMAbstractFactory.getOMFactory();
OMNamespace ns1 = factory.createOMNamespace("bar","x");
OMElement root = factory.createOMElement("root",ns1);
OMNamespace ns2 = root.declareNamespace("bar1","y");
OMElement elt1 = factory.createOMElement("foo",ns1);
OMElement elt2 = factory.createOMElement("yuck",ns2);
OMText txt1 = factory.createOMText(elt2,"blah");
elt2.addChild(txt1);
elt1.addChild(elt2);
root.addChild(elt1);

请帮助我如何序列化根元素,其中 OMElment 是非序列化 api 类。请帮我举个例子。

最佳答案

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;


public class Example {
public static void main(String[] args) {
try {
OMFactory factory = OMAbstractFactory.getOMFactory();

OMNamespace ns1 = factory.createOMNamespace("bar", "x");
OMElement root = factory.createOMElement("root", ns1);
OMNamespace ns2 = root.declareNamespace("bar1", "y");

OMElement elt1 = factory.createOMElement("foo", ns1);
OMElement elt2 = factory.createOMElement("yuck", ns2);
OMElement elt3 = factory.createOMElement("yuck2", ns2);

OMText txt1 = factory.createOMText(elt2, "blah");
OMText txt2 = factory.createOMText(elt3, "blah-blah");

elt2.addChild(txt1);
elt3.addChild(txt2);
elt1.addChild(elt2);
elt1.addChild(elt3);

root.addChild(elt1);

OutputStream outputStream = null;
try {
outputStream = new FileOutputStream("C:\\xml.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
root.serialize(outputStream);

root.serialize(System.out);

} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}

控制台输出:

<x:root xmlns:x="bar" xmlns:y="bar1"><x:foo><y:yuck>blah</y:yuck><y:yuck2>blah-blah</y:yuck2></x:foo></x:root>

序列化文件:

<x:root xmlns:x="bar" xmlns:y="bar1">
<x:foo>
<y:yuck>blah</y:yuck>
<y:yuck2>blah-blah</y:yuck2>
</x:foo>
</x:root>

更多详情

关于java - 使用 apache axiom 生成示例 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21725687/

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