我想使用Java生成保存其架构以及包含的xml数据的xml文件,据我所知,在C#.NET中是可能的。在Java中是否可能?
我的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文件包含数据以及架构,我需要使用java从架构中生成此类文件。
我只能使用jaxb创建xml部分,而我的代码的主要部分如下所示
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);
但我无法将内联xml架构部分与xml文件一起添加。
@jtahlborn好的,我会尽力感谢您的帮助。我还有一个问题,我听说stax优于dom到xml编写,因此我想使用stax来设置名称空间和其他内容。我还有一个问题,那就是jaxb仅用于将xml转换为xml模式(un marshaling),而将xml模式转换为xml(marshaling),如果我需要编写xml文件,那么我们需要使用jaxb [DOM,STAX(stream)基于阅读的写作),SAX(仅流阅读)]。
最佳答案
你会:
根据您的架构创建DOM文档(例如,解析架构文件)
创建一个新的DOM文档
将根节点添加到新的DOM文档中(例如“交易”)
将步骤1中的模式文档附加为“ transaction”元素的第一个子元素
附加实际文档数据作为“事务”元素的后续子级
或者,如果要使用JAXB生成“主” xml输出,则可以:
填充jaxb模型(从模式创建)
将jaxb模型编组到DOM文档
根据您的架构创建DOM文档(例如,解析架构文件)
将步骤3中的模式文档插入。作为DOM文档中“事务”元素的第一个子元素
(通过一些jaxb配置技巧,您可能可以使Transaction模型具有Element“ schema”属性,然后可以从解析的架构文档中设置该属性并一次封送整个模型)