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);
Advertisement
Answer
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);
}
}