简体   繁体   中英

XML parsing returns null

I am parsing the below XML using the Dom Parser.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<company>
    <Staff id="1">
        <firstname>Achyut</firstname>
        <lastname>khanna</lastname>
        <nickname>Achyut</nickname>
        <salary>900000</salary>
    </Staff>
</company>

If I only need firstName from the XML why is returning null ?

private String getNodeValue(Node node) {
        Node nd = node.getFirstChild();     
        try {
            if (nd == null) {
                return node.getNodeValue();             
            }
            else {              
                 getNodeValue(nd);
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

You must fetch the nodelist and then pass the appropriate Node value as parameter when you call your defined function.

NodeList n = item.getElementsByTagName("Staff");

Then call your function

String firstName = getNodeValue(n.item(0));

First of all, I do not recommend parsing XMLs using DOM traversals. I would recommend you to use the OXMs (JaxB or XMLbeans). But still if you are interested in doing it this way:

Here is the code

public class T2 {
public static void main(String []args) throws ParserConfigurationException, SAXException, IOException{
DocumentBuilder db = null;

String xmlString = "<?xml version='1.0' encoding='UTF-8' standalone='no'?><company>    <Staff id='1'>        <firstname>Achyut</firstname>        <lastname>khanna</lastname>        <nickname>Achyut</nickname>        <salary>900000</salary>    </Staff></company>";
Document doc = null;
InputSource is = new InputSource();

is.setCharacterStream(new StringReader(xmlString));

    db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    doc = db.parse(is);

    NodeList nodes = doc.getElementsByTagName("firstname");

    for (int i = 0; i < nodes.getLength(); i++) {
        if (nodes.item(i) instanceof Element) {
             Node node = (Node) nodes.item(i);
            nodes.item(i);

            String fName  = getCharacterDataFromElement(node);
            System.out.println(fName);
        }
    }


}
private static String getCharacterDataFromElement(Node e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return null;
}
}

The code above prints Achyut

Save yourself a lot of code by using XPath instead:

XPath xp = XPathFactory.newInstance().newXPath();
InputSource in = new InputSource(...);
String fn = xp.evaluate("/company/Staff[@id='1']/firstname/text()", in);
System.out.println(fn);

printts:

Achyut

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