getAttributeValue返回null Java

时间:2020-10-08 14:18:27

标签: java xml jdom

我想获取根元素类型的值。

如果我尝试使用getAttributeValue(“ type”),它将返回空值

此处是示例xml和代码。我正在使用org.jdom2.Element进行解析 帮助将被申请。

示例xml

<root type="new">
<msg size="30">

<attr uid="0" value="500" />
<attr uid="15" value="XHYs5"/>

</msg>
</root>

我的代码

        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File(filename);

        Document document;
        try {
            document = (Document) builder.build(xmlFile);
        } catch (JDOMException | IOException e1) {
           throw new ISOException("Error reading xml file");
        }
        Element rootNode = document.getRootElement();
        typeVal=rootNode.getAttributeValue("type");  
        System.out.println(typeVal);   

1 个答案:

答案 0 :(得分:0)

也许您的imports不好。您的代码对我有用。

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;

public class DemoTest {
    public static void main(String[] args) {
        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("E:\\git\\src\\datamigrationGeneric\\test\\sample.xml");

        Document document = null;
        try {
            document = (Document) builder.build(xmlFile);
        } catch (JDOMException | IOException e1) {
            e1.printStackTrace();
        }
        Element rootNode = document.getRootElement();
        String typeVal=rootNode.getAttributeValue("type");
        System.out.println(typeVal);

    }
}
相关问题