jaxb生成xml时在父节点生成xmlns:xsi
时间: 2023-11-20 22:04:52 浏览: 55
在使用JAXB生成XML时,如果需要在父节点生成`xmlns:xsi`属性,可以使用`javax.xml.bind.Marshaller.JAXB_SCHEMA_LOCATION`属性来指定XML Schema的位置和命名空间,并通过`javax.xml.bind.Marshaller.setProperty()`方法将该属性设置为要生成的XML中的`xmlns:xsi`属性的值。同时,需要给父节点添加一个新的属性,属性名为`xmlns:xsi`,属性值为`http://www.w3.org/2001/XMLSchema-instance`。例如:
```
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://example.com/ns path/to/schema.xsd");
Root root = new Root();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
marshaller.marshal(root, doc);
doc.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(doc), new StreamResult(System.out));
```
在这个例子中,`Marshaller.JAXB_SCHEMA_LOCATION`属性指定了XML Schema的位置和命名空间。在生成XML时,JAXB会自动将`xsi:schemaLocation`属性添加到生成的XML中,并将其值设置为`http://example.com/ns path/to/schema.xsd`。然后,通过`setAttributeNS()`方法给父节点添加一个新的属性`xmlns:xsi`,属性值为`http://www.w3.org/2001/XMLSchema-instance`。最后,使用`Transformer`将生成的XML格式化输出。例如:
```
<root xmlns="http://example.com/ns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://example.com/ns path/to/schema.xsd">
...
</root>
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)