英文:
getAttributeValue returns null java
问题
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);
英文:
i want to get the vaule of type in root element.
if i try with getAttributeValue("type") it returns null value
here the sample xml and code. i'm using org.jdom2.Element for parsing
help will be appriciated.
Sample xml
<root type="new">
<msg size="30">
<attr uid="0" value="500" />
<attr uid="15" value="XHYs5"/>
</msg>
</root>
my code
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
也许你的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);
}
}
英文:
Perhaps you have bad imports
. Your code works for me.
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论