2
以下文件TPAExtensionsType.java我從XSD文件生成了。具有屬性列表<Element>(@XmlAnyElement)的JAXB編組對象不輸出節點值
TPAExtensionsType.java
/*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TPA_Extensions_Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <any processContents='skip' maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TPA_Extensions_Type", propOrder = {
"any"
})
@XmlRootElement
public class TPAExtensionsType {
@XmlAnyElement
protected List<Element> any;
/**
* Gets the value of the any property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
*
*
*/
public List<Element> getAny() {
if (any == null) {
any = new ArrayList<Element>();
}
return this.any;
}
}
以下是獨立的應用程序,以馬歇爾上述目的爲XML。
TestUtil.java
public class TestUtil {
public static void main(String[] args) {
TPAExtensionsType tpaExtensions = new TPAExtensionsType();
Element consumerInfo = new DOMElement("ConsumerInfo");
consumerInfo.setNodeValue("Some Info");
tpaExtensions.getAny().add(consumerInfo);
StringWriter sw = new StringWriter();
JAXBContext context;
try {
context = JAXBContext.newInstance(TPAExtensionsType.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(tpaExtensions, sw);
System.out.println(sw.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
以下是輸出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<tpaExtensionsType xmlns="SOME_NAMESPACE_ HERE">
<ConsumerInfo xmlns="" xmlns:ns2="SOME_NAMESPACE_ HERE"/>
</tpaExtensionsType>
問題,我面對:
ConsumerInfo已創建的節點,但它的價值是不可見的生成的XML,儘管我已經在上面的獨立應用程序中設置了它的值。任何人都可以幫助我解決這個問題,什麼是造成這個問題?
由於Sahil.Your建議worked.However我能找到一個命名空間得到所附作爲像在前面粗斜體中所示的一個元件consumerInfo一個屬性:** < consumerInfo _xmlns:ns2 =「有些NAMESPACE HERE」_xmlns =「」>一些信息 consumerInfo> **。這可以擺脫使用JAXB? –
@JiggneshhGohel你有沒有找到你的命名空間屬性的解決方案?我遇到了完全相同的問題,並且一直在尋找解決方案 – tarares
對不起@tarares!我不記得了。我一直沒有和JAXB合作過多年。 –