Java – 读取XML文件

我试图从XML文件中读取一些数据并遇到一些麻烦,我的XML如下:

  test@test.com test2@test.com Sales Query email body message  

我试图将这些值作为字符串读入我的Java程序,到目前为止我已编写此代码:

 private static Document getDocument (String filename){ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(filename)); } catch (Exception e){ System.out.println("Error reading configuration file:"); System.out.println(e.getMessage()); } return null; } Document doc = getDocument(configFileName); Element config = doc.getDocumentElement(); 

我正在努力阅读实际的字符串值。

其中一个可能的实现:

 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(); 

与XML内容一起使用时:

  testusr testpwd  

导致"testusr""testpwd"被分配给上面的usrpwd引用。

读取xml的简单方法:

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; @XmlRootElement public 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(); } } } 

有一个关于在java中使用xml文件的好博客,如果您需要更多帮助,请查看并询问任何问题: http : //javabrainhelper.blogspot.com/2012/08/read-xml-files.html

避免硬编码尝试使下面动态的代码是它将适用于任何xml的代码我使用SAX Parser你可以使用dom,xpath它取决于你我将所有的标签名称和值存储在地图之后变得容易检索你想要的任何值我希望这会有所帮助
示例XML:

    value 1   value 2   value 3     value 4   value 5  value 6    

JAVA代码:

  import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class saxParser { static Map tmpAtrb=null; static Map xmlVal= new LinkedHashMap(); public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError { /** * We can pass the class name of the XML parser * to the SAXParserFactory.newInstance(). */ //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null); SAXParserFactory saxDoc = SAXParserFactory.newInstance(); SAXParser saxParser = saxDoc.newSAXParser(); DefaultHandler handler = new DefaultHandler() { String tmpElementName = null; String tmpElementValue = null; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { tmpElementValue = ""; tmpElementName = qName; tmpAtrb=new HashMap(); //System.out.println("Start Element :" + qName); /** * Store attributes in HashMap */ for (int i=0; i entrySet : tmpAtrb.entrySet()) { System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue()); } System.out.println("Element Value :"+tmpElementValue); xmlVal.put(tmpElementName, tmpElementValue); System.out.println(xmlVal); //Fetching The Values From The Map String getKeyValues=xmlVal.get(tmpElementName); System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues); } } @Override public void characters(char ch[], int start, int length) throws SAXException { tmpElementValue = new String(ch, start, length) ; } }; /** * Below two line used if we use SAX 2.0 * Then last line not needed. */ //saxParser.setContentHandler(handler); //saxParser.parse(new InputSource("c:/file.xml")); saxParser.parse(new File("D:/Test _ XML/file.xml"), handler); } } 

OUTPUT:

 Element Name :child1 Element Value : value 1 XmlTag::::::ValueFetchedFromTheMap: value 1 Element Name :child2 Element Value : value 2 XmlTag::::::ValueFetchedFromTheMap: value 2 Element Name :child3 Element Value : value 3 XmlTag::::::ValueFetchedFromTheMap: value 3 Element Name :child4 Element Value : value 4 XmlTag::::::ValueFetchedFromTheMap: value 4 Element Name :child5 Element Value : value 5 XmlTag::::::ValueFetchedFromTheMap: value 5 Element Name :child6 Element Value : value 6 XmlTag::::::ValueFetchedFromTheMap: value 6 Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 } 

如果使用另一个库是一个选项,以下可能更容易:

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

该库及其文档位于rasmustorkel.com