xmlns的xaxb顺序:xsi和xsi:noNamespaceSchemaLocation

时间:2013-02-07 10:15:52

标签: jaxb xml-namespaces

我正在使用JAXB创建一个xml。 用过的             marshaller.setProperty(                     Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,                     “BLA-bla.xsd”);

正在生成的xml是

<Interface xsi:noNamespaceSchemaLocation="bla-bla.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

然而,由于某种原因解析此xml的应用程序没有解析它,因为他们需要这种格式

<Interface xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="bla-bla.xsd">

更改目标应用程序不是一种选择:(

1 个答案:

答案 0 :(得分:1)

以下利用JAXB和StAX的方法似乎可以为您提供所需的输出,但由于属性的顺序并不重要,因此不能保证始终有效。

import javax.xml.bind.*;
import javax.xml.stream.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Interface.class);

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "bla-bla.xsd");
        marshaller.marshal(new Interface(), xsw);
    }

}

<强>输出

<?xml version="1.0"?><Interface xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="bla-bla.xsd"></Interface>
相关问题