首页 > 解决方案 > Updating/adding unbounded XML in Java/JAXB

问题描述

So I'm marshalling and unmarshalling XML into a List, I've got some user accounts which contain a username, current funds etc but a single user can own one or many shares.

       <xsd:complexType name="Accounts">
    <xsd:sequence>
        <xsd:element name="Username" type="xsd:string"/>
        <xsd:element name="Password" type="xsd:string"/>
        <xsd:element name="Name" type="xsd:string"/>
        <xsd:element name="Funds" type="xsd:float"/>
        <xsd:element name="ownedShares">
        <xsd:complexType>
        <xsd:sequence>
        <xsd:element name="Symbol" maxOccurs="unbounded" type="xsd:string" />
         <xsd:element name="Amount" type="xsd:int"  maxOccurs="unbounded"/>
        </xsd:sequence>
        </xsd:complexType>
        </xsd:element>
         </xsd:sequence>
        </xsd:complexType>

My problem is I don't know how to add to their owned shares, I can add new users and update existing ones, but the function parameter to update owned shares is a Accounts.OwnedShares value.

Is their a better way to format the XML so I can just insert and add and update new strings/floats into the accounts XML?

If it helps I want my XML to look a little like this -

  <Username>Test</Username>
    <Password>Test</Password>
    <Name>Test</Name>
    <Funds>111</Funds>
    <Shares>
        <Company>Test</Company>
        <Amount>111</Amount>
    </Shares>
    <Shares>
        <Company>test2</Company>
        <Amount>10</Amount>
    </Shares>
</Account>

标签: javaxmljaxb

解决方案


将以下内容添加到您的AccountXSD 架构中以Shares正确添加:

<xs:sequence minOccurs="0" maxOccurs="unbounded">
  <xs:element name="Shares">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Company" type="xs:string"/>
        <xs:element name="Amount" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:sequence>

有关 XSD 序列的详细信息和示例,请参阅此 W3C 页面


推荐阅读