Java:编组对象 - 删除 xml 中额外的 ns2 注释
我正在尝试根据定义的架构将对象内的数据编组到 xml 文件中。但是,当我打印 xml 文件时,我在 xml 标签上收到了额外的注释。有什么方法可以摆脱额外的名称空间注释(即 ns2)
这是我从编组收到的 xml 的示例。
<?xml version="1.0" encoding="UTF-8" standalone="yes">
<root xmlns:ns2="http://www.something.com/something">
<ns2:food>steak</ns2:food>
<ns2:beverage>water</ns2:beverage>
</root>
我想要的是这样的:
<?xml version="1.0" encoding="UTF-8" standalone="yes">
<root xmlns="http://www.something.com/something">
<food>steak</food>
<beverage>water</beverage>
</root>
这就是我的 Java 代码正在做的事情:
JAXBContext context = JAXBContext.newInstance("com.schema");
JAXBElement<FoodSchema> element = new JAXBElement<FoodSchema>
(new QName("FoodSchema"), Food.class, foodSchema);
Marshaller marshaller = context.createMarshaller();
OutputStream os = new FileOutputStream(object.getFilePath());
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(element, os);
非常感谢任何帮助!谢谢!
I am trying to marshall data within an object into an xml file based on a defined schema. However when I print out the xml file, I recieve extra annotations on the xml tags. Is there any way to get rid of the extra namespace annotation (i.e. ns2)
This is an example of the xml I receive from marshalling.
<?xml version="1.0" encoding="UTF-8" standalone="yes">
<root xmlns:ns2="http://www.something.com/something">
<ns2:food>steak</ns2:food>
<ns2:beverage>water</ns2:beverage>
</root>
What I want is something like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes">
<root xmlns="http://www.something.com/something">
<food>steak</food>
<beverage>water</beverage>
</root>
This is what my Java code is doing:
JAXBContext context = JAXBContext.newInstance("com.schema");
JAXBElement<FoodSchema> element = new JAXBElement<FoodSchema>
(new QName("FoodSchema"), Food.class, foodSchema);
Marshaller marshaller = context.createMarshaller();
OutputStream os = new FileOutputStream(object.getFilePath());
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(element, os);
Any help is much appreciated! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过将命名空间 URI(“http://www.something.com/something”)添加到用于构造 JAXB 元素的
QName
,并利用包级别@XmlSchema
注释将为您提供所需的名称空间限定:package-info
Food
Demo
Output
By adding a namespace URI ("http://www.something.com/something") to the
QName
used to construct the JAXB element, and leveraging the package level@XmlSchema
annotation will get you the namespace qualification that you are looking for:package-info
Food
Demo
Output
添加到 xsd 架构定义 elementFormDefault 和 attributeFormDefault:
add to xsd schema definition elementFormDefault and attributeFormDefault:
感谢您的回答。只是给出示例代码
之前:
之后:
和多余的“ns:”被删除。
Thanks for answer. Just to give sample code
before:
after:
and extra "ns:" was removed.