1

我正在XML使用 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>

如果我只需要 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;
    }
4

3 回答 3

1

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

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

然后调用你的函数

String firstName = getNodeValue(n.item(0));
于 2013-09-02T09:47:04.440 回答
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);

打印:

Achyut
于 2013-09-02T11:59:52.907 回答
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

于 2013-09-02T09:46:03.277 回答