これが回答されている場合は申し訳ありませんが、私が使用している検索用語 (つまり、 JAXB @XmlAttribute condensedまたはJAXB XML marshal to String different results ) は何も思いつきません。
私は JAXB を使用して、注釈@XmlElement
と@XmlAttribute
注釈が付けられたオブジェクトをアン/マーシャリングしています。2 つのメソッドを提供するフォーマッタ クラスがあります。1 つはマーシャル メソッドをラップし、マーシャルするオブジェクトをOutputStream
受け入れます。残念ながら、これらのメソッドは同じオブジェクトに対して同じ出力を提供しません。ファイルにマーシャリングする場合、内部的に でマークされた単純なオブジェクト フィールドは次のように出力@XmlAttribute
されます。
<element value="VALUE"></element>
一方、文字列にマーシャリングする場合は次のようになります。
<element value="VALUE"/>
私はどちらの場合も 2 番目の形式を好みますが、違いをどのように制御するかについて興味があり、関係なく同じであることに満足しています。両方のメソッドが異なるインスタンス値を排除するために使用する 1 つの静的マーシャラーも作成しました。書式設定コードは次のとおりです。
/** Marker interface for classes which are listed in jaxb.index */
public interface Marshalable {}
/** Local exception class */
public class XMLMarshalException extends BaseException {}
/** Class which un/marshals objects to XML */
public class XmlFormatter {
private static Marshaller marshaller = null;
private static Unmarshaller unmarshaller = null;
static {
try {
JAXBContext context = JAXBContext.newInstance("path.to.package");
marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
unmarshaller = context.createUnmarshaller();
} catch (JAXBException e) {
throw new RuntimeException("There was a problem creating a JAXBContext object for formatting the object to XML.");
}
}
public void marshal(Marshalable obj, OutputStream os) throws XMLMarshalException {
try {
marshaller.marshal(obj, os);
} catch (JAXBException jaxbe) {
throw new XMLMarshalException(jaxbe);
}
}
public String marshalToString(Marshalable obj) throws XMLMarshalException {
try {
StringWriter sw = new StringWriter();
return marshaller.marshal(obj, sw);
} catch (JAXBException jaxbe) {
throw new XMLMarshalException(jaxbe);
}
}
}
/** Example data */
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class Data {
@XmlAttribute(name = value)
private String internalString;
}
/** Example POJO */
@XmlType
@XmlRootElement(namespace = "project/schema")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container implements Marshalable {
@XmlElement(required = false, nillable = true)
private int number;
@XmlElement(required = false, nillable = true)
private String word;
@XmlElement(required = false, nillable = true)
private Data data;
}
marshal(container, new FileOutputStream("output.xml"))
とを呼び出した結果はmarshalToString(container)
次のとおりです。
ファイルへの出力
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:container xmlns:ns2="project/schema">
<number>1</number>
<word>stackoverflow</word>
<data value="This is internal"></data>
</ns2:container>
と
文字列に出力
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:container xmlns:ns2="project/schema">
<number>1</number>
<word>stackoverflow</word>
<data value="This is internal"/>
</ns2:container>