How to read XML file from sdcard and parse it?


Last Updated:

  1. rohit_deshmukh11

    rohit_deshmukh11 New Member This Topic's Starter

    Joined:
    Dec 30, 2009
    Messages:
    3
    Likes Received:
    0
    I want to access the XML file from sdcard and i want to parse thar file. How ta access this file and pass it to Parse method?
     

    Advertisement
  2. tliebeck

    tliebeck VIP Member VIP Member

    Joined:
    Dec 6, 2009
    Messages:
    211
    Likes Received:
    123
    Create a java.io.File object representing the file on the sdcard, then create a FileReader / FileInputStream around it.

    If you want to get access to it as a DOM, just use the standard JAXP DocumentBuilder stuff to read it.

    Feel free to take anything you need from the following example if you're unfamiliar with the DOM API...the static load() method can load a DOM from a reader or input stream.

    (Security note...the "entity resolver" bit is CRITICAL to avoid a giant security hole in the DOM API)

    Code (Text):
    1.  
    2. package nextapp.websharing.util;
    3.  
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.io.PrintStream;
    7. import java.io.PrintWriter;
    8. import java.io.StringWriter;
    9. import java.util.ArrayList;
    10. import java.util.List;
    11. import java.util.Properties;
    12.  
    13. import javax.xml.parsers.DocumentBuilder;
    14. import javax.xml.parsers.DocumentBuilderFactory;
    15. import javax.xml.parsers.ParserConfigurationException;
    16.  
    17.  
    18. import org.w3c.dom.DOMImplementation;
    19. import org.w3c.dom.Document;
    20. import org.w3c.dom.DocumentType;
    21. import org.w3c.dom.Element;
    22. import org.w3c.dom.Node;
    23. import org.w3c.dom.NodeList;
    24. import org.w3c.dom.Text;
    25. import org.xml.sax.EntityResolver;
    26. import org.xml.sax.InputSource;
    27. import org.xml.sax.SAXException;
    28.  
    29. /**
    30.  * A utility class which provides methods for working with a W3C DOM.
    31.  */
    32. public class DomUtil {
    33.    
    34.     /**
    35.      * Entity resolver which throws a SAXException when invoked to avoid external entity injection.
    36.      */
    37.     private static final EntityResolver entityResolver = new EntityResolver() {
    38.    
    39.         /**
    40.          * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
    41.          */
    42.         public InputSource resolveEntity(String publicId, String systemId)
    43.         throws SAXException, IOException {
    44.             throw new SAXException("External entities not supported.");
    45.         }
    46.     };
    47.  
    48.     /**
    49.      * ThreadLocal cache of <code>DocumentBuilder</code> instances.
    50.      */
    51.     private static final ThreadLocal<DocumentBuilder> documentBuilders = new ThreadLocal<DocumentBuilder>() {
    52.    
    53.         /**
    54.          * @see java.lang.ThreadLocal#initialValue()
    55.          */
    56.         protected DocumentBuilder initialValue() {
    57.             try {
    58.                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    59.                 DocumentBuilder builder = factory.newDocumentBuilder();
    60.                 builder.setEntityResolver(entityResolver);
    61.                 return builder;
    62.             } catch (ParserConfigurationException ex) {
    63.                 throw new RuntimeException(ex);
    64.             }
    65.         }
    66.     };
    67.    
    68.     /**
    69.      * Creates a new document.
    70.      *
    71.      * @param qualifiedName the qualified name of the document type to be
    72.      *        created
    73.      * @param publicId the external subset public identifier
    74.      * @param systemId the external subset system identifier
    75.      * @param namespaceUri the namespace URI of the document element to create
    76.      */
    77.     public static Document createDocument(String qualifiedName, String publicId, String systemId, String namespaceUri) {
    78.         DOMImplementation dom = DomUtil.getDocumentBuilder().getDOMImplementation();
    79.         DocumentType docType = dom.createDocumentType(qualifiedName, publicId, systemId);
    80.         Document document = dom.createDocument(namespaceUri, qualifiedName, docType);
    81.         if (namespaceUri != null) {
    82.             document.getDocumentElement().setAttribute("xmlns", namespaceUri);
    83.         }
    84.         return document;
    85.     }
    86.  
    87.     /**
    88.      * Retrieves a thread-specific <code>DocumentBuilder</code>.
    89.      *
    90.      * @return the <code>DocumentBuilder</code> serving the current thread.
    91.      */
    92.     public static DocumentBuilder getDocumentBuilder() {
    93.         return (DocumentBuilder) documentBuilders.get();
    94.     }
    95.    
    96.     /**
    97.      * Determines whether a specific boolean flag is set on an element.
    98.      *
    99.      * @param element The element to analyze.
    100.      * @param attributeName The name of the boolean 'flag' attribute.
    101.      * @return True if the value of the attribute is 'true', false if it is
    102.      *         not or if the attribute does not exist.
    103.      */
    104.     public static boolean getBooleanAttribute(Element element, String attributeName) {
    105.         String value = element.getAttribute(attributeName);
    106.         if (value == null) {
    107.             return false;
    108.         } else if (value.equals("true")) {
    109.             return true;
    110.         } else {
    111.             return false;
    112.         }
    113.     }
    114.  
    115.     /**
    116.      * Retrieves the first immediate child element of the specified element  
    117.      * whose name matches the provided <code>name</code> parameter.
    118.      *
    119.      * @param parentElement The element to search.
    120.      * @param name The name of the child element.
    121.      * @return The child element, or null if none was found.
    122.      */
    123.     public static Element getChildElementByTagName(Element parentElement, String name) {
    124.         NodeList nodes = parentElement.getChildNodes();
    125.         int length = nodes.getLength();
    126.         for (int index = 0; index < length; ++index) {
    127.             if (nodes.item(index).getNodeType() == Node.ELEMENT_NODE
    128.                     && name.equals(nodes.item(index).getNodeName())) {
    129.                 return (Element) nodes.item(index);
    130.             }
    131.         }
    132.         return null;
    133.     }
    134.    
    135.     public static String getPropertyElementValue(Element parentElement, String propertyElementName) {
    136.         Element childElement = getChildElementByTagName(parentElement, propertyElementName);
    137.         if (childElement == null) {
    138.             return null;
    139.         }
    140.         return getElementText(childElement);
    141.     }
    142.    
    143.     /**
    144.      * Retrieves all immediate child elements of the specified element whose
    145.      * names match the provided <code>name</code> parameter.
    146.      *
    147.      * @param parentElement The element to search.
    148.      * @param name The name of the child element.
    149.      * @return An array of matching child elements.
    150.      */
    151.     public static Element[] getChildElementsByTagName(Element parentElement, String name) {
    152.         List<Element> children = new ArrayList<Element>();
    153.         NodeList nodes = parentElement.getChildNodes();
    154.         int length = nodes.getLength();
    155.         for (int index = 0; index < length; ++index) {
    156.             if (nodes.item(index).getNodeType() == Node.ELEMENT_NODE
    157.                     && name.equals(nodes.item(index).getNodeName())) {
    158.                 children.add((Element) nodes.item(index));
    159.             }
    160.         }
    161.         return (Element[]) children.toArray();
    162.     }
    163.  
    164.     /**
    165.      * Counts the number of immediate child elements of the specified element
    166.      * whose names match the provided <code>name</code> parameter.
    167.      *
    168.      * @param parentElement The element to analyze.
    169.      * @param name The name of the child element.
    170.      * @return The number of matching child elements.
    171.      */
    172.     public static int getChildElementCountByTagName(Element parentElement, String name) {
    173.         NodeList nodes = parentElement.getChildNodes();
    174.         int length = nodes.getLength();
    175.         int count = 0;
    176.         for (int index = 0; index < length; ++index) {
    177.             if (nodes.item(index).getNodeType() == Node.ELEMENT_NODE
    178.                     && name.equals(nodes.item(index).getNodeName())) {
    179.                 ++count;
    180.             }
    181.         }
    182.         return count;
    183.     }
    184.    
    185.     /**
    186.      * Returns the text content of a DOM <code>Element</code>.
    187.      *
    188.      * @param element The <code>Element</code> to analyze.
    189.      */
    190.     public static String getElementText(Element element) {
    191.         NodeList children = element.getChildNodes();
    192.         int childCount = children.getLength();
    193.         for (int index = 0; index < childCount; ++index) {
    194.             if (children.item(index) instanceof Text) {
    195.                 Text text = (Text) children.item(index);
    196.                 return text.getData();
    197.             }
    198.         }
    199.         return null;
    200.     }
    201.  
    202.     /**
    203.      * Returns a new DOM from an <code>InputStream</code>.
    204.      *
    205.      * @param in an <code>InputStream</code> providing the XML source
    206.      * @return a DOM
    207.      */
    208.     public static Document load(InputStream in)
    209.     throws SAXException {
    210.         try {
    211.             Document document = getDocumentBuilder().parse(in);
    212.             in.close();
    213.             return document;
    214.         } catch (SAXException ex) {
    215.             throw new SAXException("Provided InputStream cannot be parsed: " + ex.toString());
    216.         } catch (IOException ex) {
    217.             throw new SAXException("Provided InputStream cannot be parsed: " + ex.toString());
    218.         }
    219.     }
    220.    
    221.     public static void log(PrintStream out, String prefix, Document document) {
    222.         try {
    223.             out.println ("[" + prefix + "] --------------------------------------------------------");
    224.             StringWriter w = new StringWriter();
    225.             DomUtil.save(document, new PrintWriter(w), null);
    226.             String s = w.toString();
    227.             s = s.replaceAll(">\\s*<", ">\n<");
    228.             out.println(s);
    229.         } catch (SAXException ex) {
    230.             ex.printStackTrace(out);
    231.         }
    232.     }
    233.  
    234.     /**
    235.      * Returns a new DOM from an <code>InputStream</code>.
    236.      *
    237.      * @param in an <code>InputStream</code> providing the XML source
    238.      * @return a DOM
    239.      */
    240.     public static Document load(InputSource in)
    241.     throws SAXException {
    242.         try {
    243.             Document document = getDocumentBuilder().parse(in);
    244.             return document;
    245.         } catch (SAXException ex) {
    246.             throw new SAXException("Provided InputStream cannot be parsed: " + ex.toString());
    247.         } catch (IOException ex) {
    248.             throw new SAXException("Provided InputStream cannot be parsed: " + ex.toString());
    249.         }
    250.     }
    251.    
    252.     public static void save(Document document, PrintWriter w, Properties outputProperties)
    253.     throws SAXException {
    254.         DomTransform.transform(document, w);
    255.     }
    256.  
    257.     /**
    258.      * Sets the text content of a DOM <code>Element</code>.
    259.      *
    260.      * @param element The <code>Element</code> to modify.
    261.      * @param value The new text value.
    262.      */
    263.     public static void setElementText(Element element, String value) {
    264.         NodeList children = element.getChildNodes();
    265.         int childCount = children.getLength();
    266.         for (int index = 0; index < childCount; ++index) {
    267.             if (children.item(index) instanceof Text) {
    268.                 Text text = (Text) children.item(index);
    269.                 text.setData(value);
    270.                 return;
    271.             }
    272.         }
    273.         Text text = element.getOwnerDocument().createTextNode(value);
    274.         element.appendChild(text);
    275.     }
    276.    
    277.     public static Element setPropertyElementValue(Element parentElement, String propertyName, String propertyValue) {
    278.         Element propertyElement = parentElement.getOwnerDocument().createElement(propertyName);
    279.         if (propertyValue != null) {
    280.             propertyElement.appendChild(parentElement.getOwnerDocument().createTextNode(propertyValue));
    281.         }
    282.         parentElement.appendChild(propertyElement);
    283.         return propertyElement;
    284.     }
    285.    
    286.     /** Non-instantiable class. */
    287.     private DomUtil() { }
    288. }
    289.  
    290.  
     

Share This Page

Loading...