XML解析返回null

时间:2013-09-02 09:38:12

标签: java xml xml-parsing

我正在使用Dom Parser解析下面的XML

<?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>

如果我只需要XML中的firstName,为什么返回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;
    }

3 个答案:

答案 0 :(得分:1)

您必须获取节点列表,然后在调用已定义的函数时将相应的Node值作为参数传递。

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

然后调用你的函数

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

答案 1 :(得分:0)

首先,我不建议使用DOM遍历解析XML。我建议你使用OXM(JaxB或XMLbeans)。但是如果你有兴趣这样做的话:

这是代码

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

上面的代码打印Achyut

答案 2 :(得分:0)

通过使用XPath来节省大量代码:

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