简体   繁体   English

使用XMLReader解组JAXB时的未读属性

[英]Unread attributes when JAXB unmarshalling with XMLReader

So far, I've been unmarshalling XML with this code: 到目前为止,我一直在使用以下代码解组XML:

JAXBContext jc = JAXBContext.newInstance(clasz);
Unmarshaller u = jc.createUnmarshaller();
StringReader reader = new StringReader(xml);
return (T) u.unmarshal(reader);

However, since I now need to set some security features (such as preventing the access of external DTDs, I'm doing it like this: 但是,由于我现在需要设置一些安全功能(例如防止访问外部DTD,所以我这样做是这样的:

JAXBContext jc = JAXBContext.newInstance(clasz);
SAXParserFactory spf = SAXParserFactory.newInstance();
XMLReader xmlReader = spf.newSAXParser().getXMLReader();

// Parser feature switch
// spf.setFeature("http://xml.org/sax/features/external-general-entities", false);

InputSource inputSource = new InputSource(new StringReader(xml));
SAXSource source = new SAXSource(xmlReader, inputSource);

Unmarshaller u = jc.createUnmarshaller();
return (T) u.unmarshal(source);

Strangely though, the results are different. 但是奇怪的是,结果却不同。 In the second case, none of my xml attributes are read. 在第二种情况下,没有读取我的xml属性。 For instance, 例如,

<a with="MO2+IG4+IG5+XZ0" ned="N02">41560113</a>

corresponds to object A, but its attributes with and ned are empty with the second code, whereas the value is correctly read. 对应于对象A,但第二个代码的和的属性为空,而正确读取了该值。

Any hints at what may cause this problem, or possible solutions would be greatly appreciated. 任何可能导致此问题的提示或可能的解决方案将不胜感激。 (note that my xml is not using namespaces) (请注意,我的xml没有使用名称空间)

I'm not entirely sure why was causing this issue, but I've solved it differently. 我不完全确定为什么会导致此问题,但是我以不同的方式解决了它。

So, hoping this helps anyone: 因此,希望这对任何人有帮助:

JAXBContext jc = JAXBContext.newInstance(clasz);

XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_VALIDATING, validate);
xif.setProperty(XMLInputFactory.SUPPORT_DTD, supportDTD);
xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, supportExternalEntities);
XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

Unmarshaller u = jc.createUnmarshaller();
return (T) u.unmarshal(xsr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM