使用jaxb的XML解析器

时间:2013-05-21 11:38:41

标签: java xml jaxb

如何使用jaxb获取嵌套xml的对象。我有以下XML -

<?xml version="1.0" ?>
    <file>
    <markups>
    <markup>
        <author>author</author>
        <name>3w2fg</name>
        <source>Mobile_iPad</source>
        <createdOn>2013-05-20T11:22:23</createdOn>
        <entities>
            <entity>
                <entityWdth>209</entityWdth>
                <entityColor>
                    <red>127.5</red>
                    <green>0</green>
                    <blue>127.5</blue>
                </entityColor>
                <entityFillColor>
                    <red>227.5</red>
                    <green>0</green>
                    <blue>327.5</blue>
                </entityFillColor>
                <entityRadian>0</entityRadian>
                <entityEndY>304</entityEndY>
                <entityStX>438</entityStX>
                <entityTypeCode>7</entityTypeCode>
                <entityPageNo>1</entityPageNo>
                <entityHt>183</entityHt>
                <entityCenterX>542.5</entityCenterX>
                <entityName>Rectangle</entityName>
                <entityStY>121</entityStY>
                <entityEndX>647</entityEndX>
                <entityCenterY>212.5</entityCenterY>
            </entity>
        </entities>
    </markup>
</markups>
<name>7987ab12-4915-49e5-8bbd-f98d6054ef6b.JPG</name>
<fileName>IMG_0008.JPG</fileName>
</file>

我正在使用jaxb将其解组为 -

JAXBContext jbContext = JAXBContext.newInstance(com.arc.markupinfo.generated.File.class);
com.arc.markupinfo.generated.ObjectFactory factory = new    com.arc.markupinfo.generated.ObjectFactory();
com.arc.markupinfo.generated.File fileObj = factory.createFile();
Unmarshaller unmarshaller = jbContext.createUnmarshaller();
fileObj = (com.arc.markupinfo.generated.File) unmarshaller.unmarshal(new   File(xmlLocation));
fileObj.getFileName();

使用除entityColor.Red ...和entityFillColor.Red之外的所有值创建对象....这些值为0,0,0,而xml显示它具有正确的值

1 个答案:

答案 0 :(得分:1)

entityColor.Red ...和entityFillColor.Red ... 的类型为intInteger)。
对于Color对象中的颜色,请使用doubleDouble),floatFloat)或String

@XmlAccessorType(XmlAccessType.FIELD)
public class Entity 
{
   //...
   private Color entityColor;
   private Color entityFillColor;
   //...
}  

@XmlAccessorType(XmlAccessType.FIELD)
public class Color 
{
   private double red;   // or float, or String
   private double green; // or float, or String
   private double blue;  // or float, or String
}  

您也可以通过最简单的方式解组您的示例:

File file = javax.xml.bind.JAXB
   .unmarshal(new java.io.File(xmlLocation),File.class);