有没有办法使用jaxb添加xml内联架构

时间:2012-03-31 20:37:15

标签: java xml jaxb xsd

有没有办法使用jaxb使用xml添加内联架构?我想表示我需要使用架构生成的xml文件添加架构。我给出了下面给出的考试

<transaction>
  <xs:schema id="transaction" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="transaction" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="id">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="in" type="xs:string" minOccurs="0" />
                <xs:element name="sn" type="xs:string" minOccurs="0" />
                <xs:element name="book" type="xs:string" minOccurs="0" />
                <xs:element name="author" type="xs:string" minOccurs="0" />
               </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="data">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="dateTime" type="xs:dateTime" minOccurs="0" />
                <xs:element name="key" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
          <xs:element name="productData">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="dateTime" type="xs:dateTime" minOccurs="0" />
                <xs:element name="key" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <id>
    <in>computer</in>
    <sn>1234567</sn>
    <book>JAVA</book>
    <author>klen</author>
  </id>
  <data>
    <dateTime>2011-06-24T17:08:36.3727674+05:30</dateTime>
    <key>Err</key>
  </data>
</transaction>

我只能生成xml文件,如

<transaction>
      <id>
        <in>abcd</in>
        <sn>1234567</sn>
        <book>computer</book>
        <author>klen</author>
      </id>
      <data>
        <dateTime>2011-06-24T17:08:36.3727674+05:30</dateTime>
        <key>Err</key>
      </data>
</transaction>

但我无法使用is xml添加内联xmlschema。我的xml生成的代码看起来像

        JAXBContext jaxbContext = JAXBContext.newInstance(Transaction.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT,true);
    jaxbMarshaller.marshal(transaction, file);
    jaxbMarshaller.marshal(transaction, System.out);

1 个答案:

答案 0 :(得分:1)

也许我错过了这个问题,但是什么阻止你写下两行?

Document trxDoc = .....; // this is what you have after marshalling
Document schemaDoc = .....; // this is your Schema document

Node schemaNode = trxDoc.importNode(schemaDoc.getDocumentElement(), true);
trxDoc.getDocumentElement().appendChild(schemaNode);

这里我假设你有一个Schema文档和marshal对象到DOM Node。