简体   繁体   中英

getAttributeValue returns null java

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);   

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);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM