0

Не могу понять, как создать xml из java классов сгенерированных из xsd, есть класс Properties (и много других) отмеченный как rootElement, но как и какие классы туда подставлять мне не понятно,

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Properties_Type", propOrder = {
"property"
})
@XmlSeeAlso({
     Properties.class
 })
 public class PropertiesType {

@XmlElement(name = "Property", required = true)
protected List<PropertiesType.Property> property;

/**
 * Gets the value of the property 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 property property.
 * 
 * <p>
 * For example, to add a new item, do as follows:
 * <pre>
 *    getProperty().add(newItem);
 * </pre>
 * 
 * 
 * <p>
 * Objects of the following type(s) are allowed in the list
 * {@link PropertiesType.Property }
 * 
 * 
 */
public List<PropertiesType.Property> getProperty() {
    if (property == null) {
        property = new ArrayList<PropertiesType.Property>();
    }
    return this.property;
}


/**
 * <p>Java class for anonymous complex type.
 * 
 * <p>The following schema fragment specifies the expected content contained within this class.
 * 
 * <pre>
 * &lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="Key" type="{}String"/>
 *         &lt;element name="Value" type="{}String"/>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 * 
 * 
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "key",
    "value"
})
public static class Property {

    @XmlElement(name = "Key", required = true)
    protected String key;
    @XmlElement(name = "Value", required = true)
    protected String value;

    /**
     * Gets the value of the key property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setKey(String value) {
        this.key = value;
    }

    /**
     * Gets the value of the value property.
     * 
     * @return
     *     possible object is
     *     {@link String }
     *     
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     * 
     * @param value
     *     allowed object is
     *     {@link String }
     *     
     */
    public void setValue(String value) {
        this.value = value;
    }

}

}

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "Properties")
public class Properties
extends PropertiesType
{


}


Properties properties = new Properties();
List<PropertiesType.Property> list = properties.getProperty();

////////////////////////////////////////////////////////////////

Но из xsd у меня было сгенерировано много классов, вот ObjectFactory

//
// This file was xml by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802

// See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.14 at 12:17:11 PM MSK //

package xml;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.math.BigDecimal;

/** * This object contains factory methods for each * Java content interface and Java element interface * xml in the xml package. *

An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory {

private final static QName _ServerStatusDesc_QNAME = new QName("", "ServerStatusDesc");
private final static QName _AgencyId_QNAME = new QName("", "AgencyId");
private final static QName _SPName_QNAME = new QName("", "SPName");
private final static QName _UpdatePrivateClientManagerTaskRs_QNAME = new QName("", "UpdatePrivateClientManagerTaskRs");
private final static QName _RqUID_QNAME = new QName("", "RqUID");
private final static QName _SystemId_QNAME = new QName("", "SystemId");
private final static QName _UpdatePrivateClientManagerTaskRq_QNAME = new QName("", "UpdatePrivateClientManagerTaskRq");
private final static QName _BranchId_QNAME = new QName("", "BranchId");
private final static QName _OperUID_QNAME = new QName("", "OperUID");
private final static QName _StatusCode_QNAME = new QName("", "StatusCode");
private final static QName _StatusDesc_QNAME = new QName("", "StatusDesc");
private final static QName _CurAmt_QNAME = new QName("", "CurAmt");
private final static QName _StatusType_QNAME = new QName("", "StatusType");
private final static QName _RbBrchId_QNAME = new QName("", "RbBrchId");
private final static QName _RegionId_QNAME = new QName("", "RegionId");
private final static QName _RbTbBrchId_QNAME = new QName("", "RbTbBrchId");
private final static QName _RqTm_QNAME = new QName("", "RqTm");

/**
 * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: xml
 * 
 */
public ObjectFactory() {
}

/**
 * Create an instance of {@link PropertiesType }
 * 
 */
public PropertiesType createPropertiesType() {
    return new PropertiesType();
}

/**
 * Create an instance of {@link PayType }
 * 
 */
public PayType createPayType() {
    return new PayType();
}

/**
 * Create an instance of {@link OperationDataType }
 * 
 */
public OperationDataType createOperationDataType() {
    return new OperationDataType();
}

/**
 * Create an instance of {@link OperationDataType.Chat }
 * 
 */
public OperationDataType.Chat createOperationDataTypeChat() {
    return new OperationDataType.Chat();
}

/**
 * Create an instance of {@link OperationDataType.Chat.Events }
 * 
 */
public OperationDataType.Chat.Events createOperationDataTypeChatEvents() {
    return new OperationDataType.Chat.Events();
}

/**
 * Create an instance of {@link OperationDataType.Chat.Operators }
 * 
 */
public OperationDataType.Chat.Operators createOperationDataTypeChatOperators() {
    return new OperationDataType.Chat.Operators();
}

/**
 * Create an instance of {@link UpdatePrivateClientManagerTaskRqType }
 * 
 */
public UpdatePrivateClientManagerTaskRqType createUpdatePrivateClientManagerTaskRqType() {
    return new UpdatePrivateClientManagerTaskRqType();
}

/**
 * Create an instance of {@link UpdatePrivateClientManagerTaskRsType }
 * 
 */
public UpdatePrivateClientManagerTaskRsType createUpdatePrivateClientManagerTaskRsType() {
    return new UpdatePrivateClientManagerTaskRsType();
}

/**
 * Create an instance of {@link Properties }
 * 
 */
public Properties createProperties() {
    return new Properties();
}

/**
 * Create an instance of {@link PropertiesType.Property }
 * 
 */
public PropertiesType.Property createPropertiesTypeProperty() {
    return new PropertiesType.Property();
}

/**
 * Create an instance of {@link PrimaryOperationType }
 * 
 */
public PrimaryOperationType createPrimaryOperationType() {
    return new PrimaryOperationType();
}

/**
 * Create an instance of {@link BankInfoType }
 * 
 */
public BankInfoType createBankInfoType() {
    return new BankInfoType();
}

/**
 * Create an instance of {@link ErrorInfoStatusType }
 * 
 */
public ErrorInfoStatusType createErrorInfoStatusType() {
    return new ErrorInfoStatusType();
}

/**
 * Create an instance of {@link ErrorType }
 * 
 */
public ErrorType createErrorType() {
    return new ErrorType();
}

/**
 * Create an instance of {@link OrgDataType }
 * 
 */
public OrgDataType createOrgDataType() {
    return new OrgDataType();
}

/**
 * Create an instance of {@link MasterSystemType }
 * 
 */
public MasterSystemType createMasterSystemType() {
    return new MasterSystemType();
}

/**
 * Create an instance of {@link ErrorInfoType }
 * 
 */
public ErrorInfoType createErrorInfoType() {
    return new ErrorInfoType();
}

/**
 * Create an instance of {@link OperationInfoType }
 * 
 */
public OperationInfoType createOperationInfoType() {
    return new OperationInfoType();
}

/**
 * Create an instance of {@link ExtraTermType }
 * 
 */
public ExtraTermType createExtraTermType() {
    return new ExtraTermType();
}

/**
 * Create an instance of {@link OrigCurAmtType }
 * 
 */
public OrigCurAmtType createOrigCurAmtType() {
    return new OrigCurAmtType();
}

/**
 * Create an instance of {@link StatusType }
 * 
 */
public StatusType createStatusType() {
    return new StatusType();
}

/**
 * Create an instance of {@link AcctBalType }
 * 
 */
public AcctBalType createAcctBalType() {
    return new AcctBalType();
}

/**
 * Create an instance of {@link OperationStatusType }
 * 
 */
public OperationStatusType createOperationStatusType() {
    return new OperationStatusType();
}

/**
 * Create an instance of {@link PayType.BankInfo }
 * 
 */
public PayType.BankInfo createPayTypeBankInfo() {
    return new PayType.BankInfo();
}

/**
 * Create an instance of {@link OperationDataType.AcctBal }
 * 
 */
public OperationDataType.AcctBal createOperationDataTypeAcctBal() {
    return new OperationDataType.AcctBal();
}

/**
 * Create an instance of {@link OperationDataType.Chat.Events.Event }
 * 
 */
public OperationDataType.Chat.Events.Event createOperationDataTypeChatEventsEvent() {
    return new OperationDataType.Chat.Events.Event();
}

/**
 * Create an instance of {@link OperationDataType.Chat.Operators.Operator }
 * 
 */
public OperationDataType.Chat.Operators.Operator createOperationDataTypeChatOperatorsOperator() {
    return new OperationDataType.Chat.Operators.Operator();
}

/**
 * Create an instance of {@link UpdatePrivateClientManagerTaskRqType.BankInfo }
 * 
 */
public UpdatePrivateClientManagerTaskRqType.BankInfo createUpdatePrivateClientManagerTaskRqTypeBankInfo() {
    return new UpdatePrivateClientManagerTaskRqType.BankInfo();
}

/**
 * Create an instance of {@link UpdatePrivateClientManagerTaskRsType.Status }
 * 
 */
public UpdatePrivateClientManagerTaskRsType.Status createUpdatePrivateClientManagerTaskRsTypeStatus() {
    return new UpdatePrivateClientManagerTaskRsType.Status();
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "ServerStatusDesc")
public JAXBElement<String> createServerStatusDesc(String value) {
    return new JAXBElement<String>(_ServerStatusDesc_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "AgencyId")
public JAXBElement<String> createAgencyId(String value) {
    return new JAXBElement<String>(_AgencyId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link SPNameType }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "SPName")
public JAXBElement<SPNameType> createSPName(SPNameType value) {
    return new JAXBElement<SPNameType>(_SPName_QNAME, SPNameType.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link UpdatePrivateClientManagerTaskRsType }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "UpdatePrivateClientManagerTaskRs")
public JAXBElement<UpdatePrivateClientManagerTaskRsType> createUpdatePrivateClientManagerTaskRs(UpdatePrivateClientManagerTaskRsType value) {
    return new JAXBElement<UpdatePrivateClientManagerTaskRsType>(_UpdatePrivateClientManagerTaskRs_QNAME, UpdatePrivateClientManagerTaskRsType.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "RqUID")
public JAXBElement<String> createRqUID(String value) {
    return new JAXBElement<String>(_RqUID_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "SystemId")
public JAXBElement<String> createSystemId(String value) {
    return new JAXBElement<String>(_SystemId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link UpdatePrivateClientManagerTaskRqType }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "UpdatePrivateClientManagerTaskRq")
public JAXBElement<UpdatePrivateClientManagerTaskRqType> createUpdatePrivateClientManagerTaskRq(UpdatePrivateClientManagerTaskRqType value) {
    return new JAXBElement<UpdatePrivateClientManagerTaskRqType>(_UpdatePrivateClientManagerTaskRq_QNAME, UpdatePrivateClientManagerTaskRqType.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "BranchId")
public JAXBElement<String> createBranchId(String value) {
    return new JAXBElement<String>(_BranchId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "OperUID")
public JAXBElement<String> createOperUID(String value) {
    return new JAXBElement<String>(_OperUID_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link Long }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "StatusCode")
public JAXBElement<Long> createStatusCode(Long value) {
    return new JAXBElement<Long>(_StatusCode_QNAME, Long.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "StatusDesc")
public JAXBElement<String> createStatusDesc(String value) {
    return new JAXBElement<String>(_StatusDesc_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "CurAmt")
public JAXBElement<BigDecimal> createCurAmt(BigDecimal value) {
    return new JAXBElement<BigDecimal>(_CurAmt_QNAME, BigDecimal.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "StatusType")
public JAXBElement<String> createStatusType(String value) {
    return new JAXBElement<String>(_StatusType_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "RbBrchId")
public JAXBElement<String> createRbBrchId(String value) {
    return new JAXBElement<String>(_RbBrchId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "RegionId")
public JAXBElement<String> createRegionId(String value) {
    return new JAXBElement<String>(_RegionId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "RbTbBrchId")
public JAXBElement<String> createRbTbBrchId(String value) {
    return new JAXBElement<String>(_RbTbBrchId_QNAME, String.class, null, value);
}

/**
 * Create an instance of {@link JAXBElement }{@code <}{@link XMLGregorianCalendar }{@code >}}
 * 
 */
@XmlElementDecl(namespace = "", name = "RqTm")
public JAXBElement<XMLGregorianCalendar> createRqTm(XMLGregorianCalendar value) {
    return new JAXBElement<XMLGregorianCalendar>(_RqTm_QNAME, XMLGregorianCalendar.class, null, value);
}

}

1 ответ 1

1

Вот ваши Java бины (убрал только комментарии).

Properties.class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "Properties")
public class Properties extends PropertiesType {
}

PropertiesType.class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Properties_Type", propOrder = { "property" })
@XmlSeeAlso({ Properties.class })
public class PropertiesType {

    @XmlElement(name = "Property", required = true)
    protected List<PropertiesType.Property> property;

    public List<PropertiesType.Property> getProperty() {
        if ( property == null ) {
            property = new ArrayList<PropertiesType.Property>();
        }
        return this.property;
    }

    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = { "key", "value" })
    public static class Property {

        @XmlElement(name = "Key", required = true)
        protected String key;
        @XmlElement(name = "Value", required = true)
        protected String value;

        public String getKey() {
            return key;
        }

        public void setKey(String value) {
            this.key = value;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}

Конструируем объект и сериализуем.

public static void main(String[] args) throws JAXBException {

    Property prop1 = new Property();
    prop1.setKey("key1");
    prop1.setValue("value1");

    Property prop2 = new Property();
    prop2.setKey("key2");
    prop2.setValue("value2");

    Properties properties = new Properties();
    List<PropertiesType.Property> data = properties.getProperty();
    data.add(prop1);
    data.add(prop2);

    JAXBContext context = JAXBContext.newInstance(Properties.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    StringWriter writer = new StringWriter();
    marshaller.marshal(properties, writer);
    String out = writer.toString();

    System.out.println(out);

}

Вывод

<Properties>
    <Property>
        <Key>key1</Key>
        <Value>value1</Value>
    </Property>
    <Property>
        <Key>key2</Key>
        <Value>value2</Value>
    </Property>
</Properties>

Как собирать объект в явном виде написано прямо в комментариях.

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 set method for the property property.

For example, to add a new item, do as follows:

    getProperty().add(newItem); 

5
  • Так то да, но у меня есть куча классов которые не стринги, дополнил вопрос
    – J Mas
    15 мар 2016 в 9:21
  • Извините, но это не интересно. Вы постите простыню нечитабельного кода, и не хотите думать от слова "совсем". В примере, в Properties передается тоже не String, а объект. Нет никакой сложности проделать тоже самое с любым уровнем вложенности; конструктор и коллекции - это азы языка. Упростите себе задачу. Например, чтобы передать на удаленную систему XML определенного вида нужно сериализовать класс SomeRequest, получить и десериализовать ответ в виде SomeResponse. Обычно такое взаимодействие с WEB сервисами организуется через WSDL. Возможно, вы вообще не тем занимаетесь.
    – enzo
    15 мар 2016 в 10:03
  • Я уже два дня разбираюсь с этим кодом, получился у меня такой код, PropertiesType.Property prop = new PropertiesType.Property(); и в prop есть метод только setKey and setValue только для String, и List<PropertiesType.Property> data = properties.getProperty(); data.add(prop1); принимает у меня только properties объекты, но не объекты
    – J Mas
    15 мар 2016 в 11:30
  • Кое как сгенерировал xml файл, и в итоге получается что корневой элемент совсем другой, но именно туда все setится, но marshaller ругается что он не указан корневым элементом
    – J Mas
    15 мар 2016 в 12:41
  • ничего что я вручную подставил ему аннотацию xml root, валидацию он не проходит но на экран печатает xml,
    – J Mas
    15 мар 2016 в 13:27

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.