在Java中获取XML文件的属性

时间:2016-09-09 10:27:44

标签: java xml attributes

我有以下xml文件:

<TEST>
<NEED ID="0">OK</NEED>
</TEST>

我只想获取标签NEED的属性并将其保存到Integer变量中。

@XmlRootElement(name = "TEST")
@XmlAccessorType (XmlAccessType.FIELD)
public class Resp {

    @XmlAttribute(name = "ID", required = true) 
    protected Integer resultId;
    // getters, setters, constructor
}

如何获取ID值?

1 个答案:

答案 0 :(得分:0)

您可以使用JDom解析器。

File inputFile = new File("input.xml");
SAXBuilder saxBuilder = new SAXBuilder();

Document document = saxBuilder.build(inputFile);
Element classElement = document.getRootElement();

List<Element> aList = classElement.getChildren();


for (int temp = 0; temp < aList.size(); temp++) {    
            Element student = aList.get(temp);

            Attribute attribute =  student.getAttribute("ID");
            System.out.println("ID : " 
               + attribute.getValue() ); 

         }