[英]XML parsing returns null
I am parsing the below XML
using the Dom Parser. 我正在使用Dom解析器解析以下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>
If I only need firstName from the XML why is returning null ? 如果我只需要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;
}
You must fetch the nodelist and then pass the appropriate Node value as parameter when you call your defined function. 您必须获取节点列表,然后在调用定义的函数时将适当的Node值作为参数传递。
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. 首先,我不建议使用DOM遍历来解析XML。 I would recommend you to use the OXMs (JaxB or XMLbeans). 我建议您使用OXM(JaxB或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
上面的代码打印了Achyut
Save yourself a lot of code by using XPath instead: 通过使用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: printts:
Achyut
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.