オブジェクト階層からXMLを生成するにはどうすればよいですか?
-
05-07-2019 - |
質問
正しい用語が何であれ、オブジェクト、ツリー/モデル/階層があります。これは、目的のXMLの1対1マッピングとして特徴付けられるもので構成されています。
つまり、次のようなものがあります(非標準のUML構文の場合)
class A {
class B b[*]
class C
class D
}
class B {
class C c[*]
string AttributeFoo = "bar"
}
class C {
string AttributeThis = "is"
}
class D {
string AttributeName = "d"
}
望ましい出力は次のようなものです:
<?xml version="1.0"?>
<a>
<b attribute-foo="bar">
<c attribute-this="is"/>
</b>
<c attribute-this="is"/>
<d attribute-name="d"/>
</a>
この目標を達成するための最高、および/または最も簡単な方法を提案しますか?
解決
JAXBを見るのは、標準ライブラリで a)を取得し、 b)それほど複雑ではないからです。このコードにはJava 6が必要です。
@XmlRootElement public static class A {
public List<B> b = new ArrayList<B>();
}
public static class B {
public List<C> c = new ArrayList<C>();
@XmlAttribute(name = "attribute-foo") public String attributeFoo = "foo";
}
public static class C {
@XmlAttribute(name = "attribute-this") public String attributeThis = "is";
}
public static void main(String[] args) {
A a = new A();
a.b.add(new B());
a.b.get(0).c.add(new C());
JAXB.marshal(a, System.out);
}
//TODO: getters/setters, error handling and so on
出力:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<a>
<b attribute-foo="foo">
<c attribute-this="is"/>
</b>
</a>
他のヒント
JAXBの目的だと思います( http://jaxb.java.net/ ) XMLにオブジェクトをマッピングする
ツールを使用する場合は、 jaxb をご覧ください。マーシャリング/アンマーシャリングはあなたがここでやっていることです、それは多くの解決策が利用できる一般的な問題です。
最高だと思います(車輪を再発明することはありません)そしてそれは最も簡単だと思います(手動でやったことがあり、本当に面白くありません-オブジェクトグラフは循環する可能性があります...)
XMLBeans が好きです。
もしあなたがパフォーマンスについてあまり気にしないなら、私はJaxbから離れて、より単純なフレームワークのいくつかを見てみると思います。パフォーマンスが問題になる場合、ほとんどの状況でjaxbよりjibxを優先する傾向があります。
この状況では、単純なプロジェクトを使用する傾向があります。
http://simple.sourceforge.net/download /stream/doc/tutorial/tutorial.php#start
オブジェクトモデルに注釈を付けて、すぐに移動します.....:-)
@Root
public class Example {
@Element
private String text;
@Attribute
private int index;
public Example() {
super();
}
public Example(String text, int index) {
this.text = text;
this.index = index;
}
public String getMessage() {
return text;
}
public int getId() {
return index;
}
}