JAXB XML使用/ in属性值解组

时间:2017-09-06 09:41:39

标签: java xsd xml-parsing jaxb jaxb2-maven-plugin

当某些特殊字符为" /"时,我遇到了解组XML文件的问题。包含在一个属性的值中,如下所示:

<field name = "test" value = "test&/"/>

我使用的是woodstox-core(v5.0.3)和stax2-api(3.1.4)库

属性值在XSD中定义为规范化的字符串,我认为它允许字符&#34; /&#34;:

<xs:element name="field" maxOccurs="unbounded">
    <xs:complexType>
        <xs:attribute name="name" type="xs:token" use="required" />
        <xs:attribute name="value" type="xs:normalizedString" use="required" />
    </xs:complexType>
</xs:element>

但是在进行unmarshal调用时,会抛出异常:

XMLStreamReader xsr = null;
try {
    // Create the XML stream reader
    XMLInputFactory xif = XMLInputFactory.newFactory();
    xsr = xif.createXMLStreamReader(inputStream, "UTF-8");

    // Unmarshall the XML with JAXB, with XML schema validation enabled
    JAXBContext jc = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setSchema(this.xmlSchema);
    Root rootIndex = (Root) unmarshaller.unmarshal(xsr);
    [...]
}

这里有例外:

Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character '/' (code 47) (expected a name start character)
 at [row,col {unknown-source}]: [17,74]
    at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:653) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.StreamScanner.parseFullName(StreamScanner.java:1933) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.StreamScanner.parseEntityName(StreamScanner.java:2058) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.StreamScanner.fullyResolveEntity(StreamScanner.java:1525) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.BasicStreamReader.parseAttrValue(BasicStreamReader.java:2017) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.BasicStreamReader.handleNsAttrs(BasicStreamReader.java:3145) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.BasicStreamReader.handleStartElem(BasicStreamReader.java:3043) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.BasicStreamReader.nextFromTree(BasicStreamReader.java:2919) [woodstox-core-5.0.3.jar:5.0.3]
    at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1123) [woodstox-core-5.0.3.jar:5.0.3]
    at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:197) [jaxb-impl-2.2.3-1.jar:2.2.3]
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:366) [jaxb-impl-2.2.3-1.jar:2.2.3]
    ... 16 more

我还需要定义什么才能接受这些字符(UTF-8除外)还是根本不允许?

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

这里的问题不是/字符,而是&amp;在它之前。 /它本身就可以,但是&amp;需要逃脱。由于错误信息,我太专注于/。

逃离&amp;像那样修复了这个问题:

<field name = "test" value = "test&amp;/"/>