2011-10-09 15 views
8

मैं एक 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> 

मैं में तारों के रूप में इन मूल्यों को पढ़ने के लिए कोशिश कर रहा हूँ मेरा जावा प्रोग्राम, मैंने अब तक यह कोड लिखा है:

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

की [जावा संभव डुप्लिकेट: कैसे पढ़ना और लिखना एक्सएमएल फाइलें?] (http://stackoverflow.com/questions/7373 567/जावा-कैसे-टू-रीड-एंड-राइट-एक्सएमएल-फाइलें) – AaA

उत्तर

2

वहाँ जावा में xml फाइलों के साथ काम पर एक अच्छा ब्लॉग है, तो कृपया एक नज़र लेने के लिए और किसी भी सवाल पूछने के आप और अधिक मदद की जरूरत है: http://javabrainhelper.blogspot.com/2012/08/read-xml-files.html

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

जब एक्सएमएल सामग्री के साथ प्रयोग किया है:

और "testpwd" में
<credentials> 
    <user>testusr</user> 
    <password>testpwd</password> 
</credentials> 

परिणामों के ऊपर usr और pwd संदर्भ करने के लिए आवंटित हो रही।

+0

दस्तावेज़ के लिए सही आयात क्या है? मैं कुछ देखता हूं लेकिन कोई भी सही नहीं लगता है ... –

+2

'org.w3c.dom.Document' अगर कोई अभी भी सोच रहा है – Xerus

2

पढ़ना एक्सएमएल आसान तरीका:

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

बचें hardcoding पर कोड है कि नीचे गतिशील है बनाने का प्रयास करें वह कोड है जो मैंने किसी भी एक्सएमएल के लिए काम किया है जिसे मैंने सैक्स पार्सर का उपयोग किया है, आप डोम का उपयोग कर सकते हैं, xpath यह आपके ऊपर है मैं मानचित्र में सभी टैग नाम और मूल्यों को संग्रहीत कर रहा हूं, इसके बाद मैं आपके इच्छित मूल्यों को पुनर्प्राप्त करना आसान हो जाता हूं। पे इस में मदद करता है
नमूना एक्सएमएल:

<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> 

जावा कोड:

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

उत्पादन:

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 } 
संबंधित मुद्दे