0
我想使用已定義的XSD架構編組XML:如何使用JAXB中的名稱空間編組XML?
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="myNamespace" xmlns="myNamespace">
<xs:element name="element" type="JavaBean" />
<xs:complexType name="JavaBean">
</xs:complexType>
</xs:schema>
這是空的Java bean類型:
package main;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "JavaBean")
public class JavaBean {
}
簡單測試結果「找不到元素‘元素’的聲明。「錯誤。
package main;
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
public class Test {
public static void main(String[] args) throws JAXBException, IOException, SAXException {
final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File("sample.xsd"));
JavaBean message = new JavaBean();
JAXBElement<JavaBean> element = new JAXBElement<>(new QName("element"), JavaBean.class, message);
JAXBContext context = JAXBContext.newInstance(JavaBean.class);
Marshaller jaxbMarshaller = context.createMarshaller();
jaxbMarshaller.setSchema(schema);
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(element, System.out);
}
}
有趣的是,當我從XML Schema Definition中刪除targetNamespace和xmlns時,它很好用。
我在做什麼錯?
可以忽略的命名空間的位置,同時編組像jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, 「」); – Yogi
@Yogi我想將它包含在XML中,而不是忽略它。 – Line