2016-07-22 62 views
1

多年以來,由於沒有處理過XML模式,因此在使用XML Spy中生成的模式手動解組某些XML時遇到了問題。JAXB unmarshalling模式問題:'org.xml.sax.SAXParseException cvc-elt.1'

對於我的生活,我無法解決它,儘管各種其他谷歌類似的問題/答案!

下面是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’.] 
+0

實際代碼中的XML是否是字符串?任何理由不只是將文件提供給unmarhsal()? – milez

+0

這只是示例代碼,但傳入的XML仍會導致相同的錯誤。但是,謝謝。 – deanpullen

回答

0

似乎一個空間存在「我的元素」。檢查myxsd.xsd文件

+0

謝謝,但那裏似乎沒有空間? – deanpullen

+0

然後消息找不到元素'我的元素'的聲明。很奇怪,因爲它看起來像有一個空間。也許調試薩克斯失敗可能會有所幫助 –

+0

啊道歉;我沒有意識到你在錯誤中的意思 - 這只是我複製和粘貼,然後編輯錯誤,爲了使類匿名等,空間不應該在那裏,我已經更新了錯誤。謝謝! – deanpullen

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; 
} 

也許類似上述。