【问题标题】:xmlbeans - set content of a complex typexmlbeans - 设置复杂类型的内容
【发布时间】:2009-04-10 06:57:41
【问题描述】:

我的 xsd 文件包含:

                <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>

使用 xmlbeans,我可以使用以下方法轻松设置属性:

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

我知道我可以使用 newCursor() 来设置元素的内容,但这是最好的方法吗?

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

【问题讨论】:

    标签: java xml xmlbeans


    【解决方案1】:

    我不太明白你的问题。

    我认为你的 XSD 会给你 Java 类来生成这样的 XML:

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

    你的意思是你想在一个 XML 元素中设置“内部”文本,所以你最终会得到这样的 XML?

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

    如果是这样,请将您的 XSD 更改为此,以使用嵌套元素而不是属性:

    <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>
    

    那么你就可以做到:

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

    更新

    好的 - 我现在明白了。

    试试这个:

    <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>  
    

    然后:

        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");
    

    应该这样给XML,我认为这是你想要的:

    <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>
    

    【讨论】:

    • 这是我希望我的 xml 看起来的样子:这是一些文本 “这是一些文本”位?谢谢
    【解决方案2】:

    我不确定这是否正是您要问的,但使用 XMLBeans 设置属性或元素值的最佳方法是使用 XMLBeans 生成的 getter 和 setter。

    也许为您的光标问题提供更多上下文会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-10
      • 2010-12-27
      • 1970-01-01
      • 2015-03-10
      • 2012-12-29
      • 2012-10-19
      • 2013-03-15
      • 2016-09-28
      相关资源
      最近更新 更多