问题描述
我想获取根元素类型的值。
如果我尝试使用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);
解决方法
也许您的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);
}
}