java - getAttributeValue 返回 null java
问题描述
我想在根元素中获取类型的值。
如果我尝试使用 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);
}
}
推荐阅读
- python - 在数据帧或其他数据结构中查找和寻址的最快方法
- c - 在终端中工作的命令在使用系统时不起作用
- javascript - Vue.js UI 不显示已成功请求的 Amazon S3 图像
- python - 无法弄清楚如何从我的函数中获取生成的电子邮件
- python - 为什么我的程序需要这么长时间才能执行/我完成问题的方式有问题吗?
- python - 如何使用 IronPython 2.7 接收 UDP 数据报?
- javascript - JS 未在 Rails 5.1.6 中呈现
- javascript - 在不同的屏幕尺寸下使用 Jquery 更改 css
- typo3 - 为特定表单覆盖 TYPO3 电源邮件中的密件抄送
- javascript - 扁平化嵌套数组的 Python 和 Javascript 差异