2011-10-09 133 views
8

我試圖從一個XML文件中的某些數據讀取並遇到了一些麻煩,在XML我有如下:爪哇 - 讀取XML文件

<xml version="1.0" encoding="UTF-8"?> 

<EmailSettings> 
    <recipient>[email protected]</recipient> 
    <sender>[email protected]</sender> 
    <subject>Sales Query</subject> 
    <description>email body message</description> 
</EmailSettings> 

我想作爲字符串到讀取這些值我的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(); 

雖然我在努力閱讀實際的字符串值。

+0

可能重複:如何讀寫xml文件?](http://stackoverflow.com/questions/7373 567/java-how-to-read-and-write-xml-files) – AaA

回答

16

其中一個可能實現的:

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內容中使用時:

<credentials> 
    <user>testusr</user> 
    <password>testpwd</password> 
</credentials> 

結果在"testusr""testpwd"分配到usrpwd以上參考。

+0

什麼是Document的正確導入?我看到一些但沒有一個是正確的...... –

+2

'org.w3c.dom.Document'如果有人還在想 – Xerus

2

讀取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(); 
      } 

    } 
} 
0

如果使用第三方庫是一個選項,下面可能會更容易:

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

1

避免硬編碼嘗試使該低於動態代碼是它將適用於任何xml的代碼我已經使用過SAX Parser,你可以使用dom,xpath這取決於你 我將所有的標籤名稱和值存儲在地圖中之後,它很容易檢索任何你想要的值我ho PE這有助於
示例XML:

<parent> 
<child > 
    <child1> value 1 </child1> 
    <child2> value 2 </child2> 
    <child3> value 3 </child3> 
    </child> 
    <child > 
    <child4> value 4 </child4> 
    <child5> value 5</child5> 
    <child6> value 6 </child6> 
    </child> 
    </parent> 

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<String,String> tmpAtrb=null; 
      static Map<String,String> xmlVal= new LinkedHashMap<String, String>(); 
     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<attributes.getLength(); i++) { 
         String aname = attributes.getLocalName(i); 
         String value = attributes.getValue(i); 
         tmpAtrb.put(aname, value); 
        } 

       } 

       @Override 
       public void endElement(String uri, String localName, String qName) 
                  throws SAXException { 

        if(tmpElementName.equals(qName)){ 
         System.out.println("Element Name :"+tmpElementName); 
        /** 
        * Retrive attributes from HashMap 
        */     for (Map.Entry<String, String> 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:中[Java的

Element Name :child1 
Element Value : value 1 
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1 
Element Name :child2 
Element Value : value 2 
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2 
Element Name :child3 
Element Value : value 3 
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3 
Element Name :child4 
Element Value : value 4 
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4 
Element Name :child5 
Element Value : value 5 
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5 
Element Name :child6 
Element Value : value 6 
XmlTag:<child6>:::::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 }