如何使用jaxb解析xml

时间:2013-06-18 11:19:04

标签: java xml jaxb

您好我正在尝试获取xml数据.. 结构是这样的: ....

<transport>
    <Journey>
    <JourneyPatternSection id ="JPS_13">
       <from> a</from>
       <to>b</to> 
    </JourneypatternSection>
        </Journey>
        <JourneyPattern id="JP_1_0">
                                <JourneyPatternSectionRefs>JPS_13</JourneyPatternSectionRefs>
                        </JourneyPattern>
        <VechileJourney>
        <JourneyPatternRef>JP_1_0</JourneyPatternRef>
                    <DepartureTime>17:10:00</DepartureTime>
    </VechileJourney>
</transport>

我已经使用jaxb提取了JourneypatternId,但由于旅行模式ID在vechilejourney标签中有参考,我无法获得出发时间和信息。

1 个答案:

答案 0 :(得分:2)

http://www.thaiopensource.com/relaxng/trang-manual.html下载trang.jar 转到命令提示符, 要将xml转换为xsd,请键入以下命令

java -jar trang.jar transport.xml transport.xsd

将xml结构转换为xsd后,写下命令

xjc -p com.jaxb.test.xml.beans transport.xsd

上面的命令将从transport.xsd

生成java bean

之后,您可以解压缩您的xml,如下所示

try
    {
        final JAXBContext jc = JAXBContext.newInstance(Transport.class);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        try
        {
            final Transport transport = (Transport) unmarshaller.unmarshal(new FileReader(TRANSPORT_XML));
        } catch (final FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (final JAXBException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

参考:http://shahpritesh.blogspot.in/2012/06/writing-and-reading-java-object-to-and.html