我尝试从xml文件中检索一些信息,但它返回一个null对象。我使用DOM来解析文件(参见下面的代码)。我需要一些帮助,因为我不知道这是我的逻辑还是我的代码是坏的。感谢您的时间 !
public class ReadXMLFile {
private File fXmlFile;
private Document doc;
private Contact m_contact=null;
public ReadXMLFile(String name){
try{
m_contact = new Contact();
fXmlFile = new File("/pathtofile/"+name+".xml"); //should be verified
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(fXmlFile);
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean readXml(String _id){
try{
doc.getDocumentElement().normalize();
if(doc.getDocumentElement().getNodeName().equalsIgnoreCase("listContact")){
NodeList nList = doc.getElementsByTagName("contact");
Node nNode;
nNode = nList.item(Integer.parseInt(_id));
if (nNode.getNodeName().equalsIgnoreCase("contact")){
if(nNode.getNodeType() == Node.ELEMENT_NODE){
System.out.println("\nCurrent Element :" + nNode.getNodeName());
Element eElement = (Element)nNode;//get element of node
m_contact.setId(Integer.parseInt(eElement.getAttribute("id")));
m_contact.setPhoneNumber(eElement.getAttribute("phoneNumber"));
m_contact.setName(eElement.getAttribute("name"));
m_contact.setFistName(eElement.getAttribute("firstName"));
return true;
}
}
}
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
public Contact getM_contact() {
if(m_contact!=null){
return m_contact;
}
else
return null;
}
这是我的xml结果:
<listContact>
<contact id="0">
<firstName>martin</firstName>
<lastName>dupond</lastName>
<phoneNumber>514</phoneNumber>
<synchronize>false</synchronize>
</contact>
</listContact>
输出:
Contact{id=0, phoneNumber=, name=, fistName=, synchronize=false}
答案 0 :(得分:2)
您在getAttribute
元素上使用contact
来检索firstName
等的值,但在XML中,这些不是属性,而是子元素。
如果您使用的是JDOM API,则只需使用getChild(name)
方法即可。在“标准”DOM API中,你必须经历更多的事情,例如:
Element eElement = (Element)nNode;
// only one first name element
Element firstNameElem = eElement.getElementsByTagName("firstName").item(0);
m_contact.setFistName(firstNameElem.getNodeValue());
答案 1 :(得分:1)
尝试这个,我尝试了它,它对我有用
Node nNode = nList.item(Integer.parseInt(temp));
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("phoneNumber").item(0).getTextContent());
}
return false;
....