2

美好时光!

我有一个xml:

<fieldSet name="Test" desc="Test">
  <field name="id">
    <fieldinfo>
        <name>id</name>
        <type>String</type>
        <fieldsize>50</fieldsize>
    </fieldinfo>
    <validators />
  </field>
</fieldSet>

我需要使用 JAXB 解析它。我试过这个:

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(CustomFieldSet.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            StringReader reader = new StringReader(xml);
            CustomFieldSet fieldSet = (CustomFieldSet) unmarshaller.unmarshal(reader);

        } catch (Exception e) {
            logger.error(e.getMessage(), e); 
        }

CustomFieldSet 类的开头是:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "fieldSet")
public class CustomFieldSet {

@XmlAttribute(name = "name", required = true)
private String tableName;

@XmlAttribute(name = "desc", required = true)
private String tableDescription;

    ...

当调用 unmarshal() 函数时,会抛出以下异常:

javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException: Content is not allowed in prolog.]

我认为问题与我的 xml 不包含 xml 声明 ( <?xml ...) 的事实有关。

有人知道这里的解决方法是什么吗?

4

2 回答 2

2

我已将代码更改为使用 InputStream 而不是 StringReader,现在一切正常:

try {
            XMLInputFactory xif = XMLInputFactory.newFactory();
            InputStream bis = new ByteArrayInputStream(tableDescription.getBytes("UTF-8"));
            XMLStreamReader xsr = xif.createXMLStreamReader(bis, "UTF-8");

            xsr.nextTag();

            JAXBContext jaxbContext = JAXBContext.newInstance(CustomFieldSet.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            JAXBElement<CustomFieldSet> jb = unmarshaller.unmarshal(xsr, CustomFieldSet.class);
            xsr.close();

            fieldSet = jb.getValue();

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
于 2012-11-12T10:21:20.670 回答
1

JAXB (JSR-222)实现不需要 XML 标头(即<?xml version="1.0" encoding="UTF-8"?>),请参见下面的示例。我怀疑您的示例中的 XML 字符串有一些特别之处。

Java 模型 (Foo)

package forum13341366;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    private String bar;

}

演示代码

package forum13341366;

import java.io.StringReader;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<foo><bar>Hello World</bar></foo>");
        Foo foo = (Foo) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(foo, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <bar>Hello World</bar>
</foo>

于 2012-11-12T11:07:34.847 回答