从XML文件中读取值时出错

时间:2014-03-07 11:14:38

标签: java xml

我正在尝试从XML文件中读取值,但是当我尝试将它们打印到控制台时,我得到null个值。我在这里提供我的代码以及XML文件。

XML

<?xml version="1.0" encoding="UTF-8" ?>
<customer id="1"
   age="29"
   name="jeet">
 </customer>

模型类

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }
}

驱动程序

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class CheckClass {
    public static void main(String[] args) {
        try {
            File file = new File("./file/NewFile.xml");
            JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
            System.out.println(customer.age);
            System.out.println(customer.name);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }
}

System.out.println(customer.age);
System.out.println(customer.name);给我0null个值。

请有人帮忙,谢谢。

3 个答案:

答案 0 :(得分:1)

您的问题是由于您的Java代码期望与该XML结构不匹配而引起的。您有两种选择:

将注释@XmlElement更改为@XmlAttribute

将您的xml更改为:

<?xml version="1.0" encoding="UTF-8" ?>
<customer id="1">
   <age>29</age>
   <name>jeet</name>
 </customer>

答案 1 :(得分:0)

名称和年龄属性不是元素。试试这个:

@XmlAttribute
public void setName(String name) {
    this.name = name;
}

@XmlAttribute
public void setAge(int age) {
    this.age = age;
}

答案 2 :(得分:-1)

你为什么不用 Xstream library

示例:

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

@XStreamAlias("Cat")
class Cat {
  @XStreamAsAttribute
  int age;
  String name;
}

public class XStreamDemo {

    public static void main(String[] args) {

        XStream xstream = new XStream();
        xstream.processAnnotations(Cat.class);

        String xml = "<Cat age='4' ><name>Garfield</name></Cat>";

        Cat cat = (Cat) xstream.fromXML(xml);

        System.out.println("name -> " + cat.name);
        System.out.println("age -> " + cat.age);

    }

}

您需要将Xstream jar文件添加到类路径中。