Java - Reading XML file
One of the possible implementations:
File file = new File("userdata.xml");DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance();DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();Document document = documentBuilder.parse(file);String usr = document.getElementsByTagName("user").item(0).getTextContent();String pwd = document.getElementsByTagName("password").item(0).getTextContent();
when used with the XML content:
<credentials> <user>testusr</user> <password>testpwd</password></credentials>
results in "testusr"
and "testpwd"
getting assigned to the usr
and pwd
references above.
Reading xml the easy way:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic class Customer { String name; int age; int id; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getAge() { return age; } @XmlElement public void setAge(int age) { this.age = age; } public int getId() { return id; } @XmlAttribute public void setId(int id) { this.id = id; }}
.
package com.mkyong.core;import java.io.File;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;public class JAXBExample { public static void main(String[] args) { Customer customer = new Customer(); customer.setId(100); customer.setName("mkyong"); customer.setAge(29); try { File file = new File("C:\\file.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(customer, file); jaxbMarshaller.marshal(customer, System.out); } catch (JAXBException e) { e.printStackTrace(); } }}
If using another library is an option, the following may be easier:
package for_so;import java.io.File;import rasmus_torkel.xml_basic.read.TagNode;import rasmus_torkel.xml_basic.read.XmlReadOptions;import rasmus_torkel.xml_basic.read.impl.XmlReader;public class Q7704827_SimpleRead{ public static void main(String[] args) { String fileName = args[0]; TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT); String recipient = emailNode.nextTextFieldE("recipient"); String sender = emailNode.nextTextFieldE("sender"); String subject = emailNode.nextTextFieldE("subject"); String description = emailNode.nextTextFieldE("description"); emailNode.verifyNoMoreChildren(); System.out.println("recipient = " + recipient); System.out.println("sender = " + sender); System.out.println("subject = " + subject); System.out.println("desciption = " + description); }}
The library and its documentation are at rasmustorkel.com