JAXB解组模式问题:'org.xml.sax.SAXParseException cvc-elt.1'

时间:2016-07-22 09:30:11

标签: java xml xsd jaxb

多年来没有使用过XML模式,我遇到了使用XML Spy中生成的模式手动解组某些XML的问题。

对于我的生活,我无法解决它尽管各种其他类似的google问题/回应!

这是XML(大大减少只是为了突出问题):

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

这是myxsd.xsd架构(大大减少只是为了突出问题):

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://myhost.com/Elements" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" targetNamespace="http://myhost.com/Elements" elementFormDefault="qualified" attributeFormDefault="unqualified" vc:minVersion="1.1">
    <xs:element name="myelement"/>
</xs:schema>

以下是代码:

String xml = ""; //input the XML from above.
JAXBContext context =
    JAXBContext.newInstance(MyElement.class);

Unmarshaller unmarshaller = context.createUnmarshaller();

document = (MyElement) unmarshaller.unmarshal(new StringReader(xml));

元素pojo:

@XmlRootElement(name = "myelement", namespace = "http://myhost.com/Elements")
@XmlAccessorType(XmlAccessType.FIELD) 
@XmlType(name = "myelementType", namespace = "http://myhost.com/Elements")
public class MyElement {
}

导致:

javax.xml.bind.UnmarshalException - with linked exception:[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 110; cvc-elt.1: Cannot find the declaration of element ‘myelement’.]

2 个答案:

答案 0 :(得分:0)

似乎空间出现'我的元素'。检查myxsd.xsd文件

答案 1 :(得分:0)

public static MyElement unmarshal(String str) throws JAXBException {
 JAXBContext jaxbContext = JAXBContext.newInstance(MyElement.class);
 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

 JAXBElement<MyElement> root = jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(str))), MyElement.class);
 MyElement el = root.getValue();

 return el;
}

也许就像上面那样。