Search code examples
javaxmlxmlbeans

xmlbeans - set content of a complex type


My xsd file contains:

                <xs:sequence>
                    <xs:element name="Book">
                        <xs:complexType>
                            <xs:attribute name="author" type="xs:string" />
                            <xs:attribute name="title" type="xs:string" />
                        </xs:complexType>
                    </xs:element>
                </xs:sequence>

With xmlbeans, I can set the attributes easily using:

    Book book= books.addNewBook();
    book.setTitle("The Lady and a Little Dog");

I know that I can use newCursor() to set the content of the element, but is this the best way?

object.newCursor().setTextValue(builer.toString());

Solution

  • I don't quite understand your question.

    I think your XSD will give you Java classes to produce XML like this:

    <book author="Fred" title="The Lady and a Little Dog" />
    

    Do you mean you want to set the "inner" text within an XML element, so you end up with XML like this?

    <book>
      <author>Fred</author>
      <title>The Lady and a Little Dog</title>
    </book>
    

    If so, change your XSD to this, to use nested elements rather than attributes:

    <xs:sequence>
        <xs:element name="Book">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="author" type="xs:string" />
                <xs:element name="title" type="xs:string" />
              </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:sequence>
    

    Then you'll simply be able to do:

    Book book= books.addNewBook();
    book.setAuthor("Fred");
    book.setTitle("The Lady and a Little Dog");
    

    UPDATE

    OK - I understand now.

    Try this:

    <xs:element name="Book"  minOccurs="0" maxOccurs="unbounded">
      <xs:complexType>
        <xs:simpleContent>
          <xs:extension base="xs:string">
            <xs:attribute name="author" type="xs:string" />
            <xs:attribute name="title" type="xs:string" />
          </xs:extension>
        </xs:simpleContent>
      </xs:complexType>    
    </xs:element>  
    

    And then:

        Book book1 = books.addNewBook();
        book1.setAuthor("Fred");
        book1.setTitle("The Lady and a Little Dog");
        book1.setStringValue("This is some text");
    
        Book book2 = books.addNewBook();
        book2.setAuthor("Jack");
        book2.setTitle("The Man and a Little Cat");
        book2.setStringValue("This is some more text");
    

    Which should give XML like this, which I think is what you want:

    <Book author="Fred" title="The Lady and a Little Dog">This is some text</Book>
    <Book author="Jack" title="The Man and a Little Cat">This is some more text</Book>