Domanda

I am very new to XMLParsing. It sat at work today without managing to parse a file and get it into an arrayList.

My file looks kinda like this

<type>
 <OBJECT_TYPE>horse</OBJECT_TYPE>
   <prop>blabla</prop>
   <param>black</param>
  <OBJECT_TYPE>cat</OBJECT_TYPE>
   <prop>blabla</prop>
   <param>black</param>
  <OBJECT_TYPE>car</OBJECT_TYPE>
   <prop>blabla</prop>
   <param>black</param>
</type>

But alot longer and not that content. I tried to use SaxParser but no success. And I have read pretty much every SaxParser turials around but all parse xml that has attibutes and my XML doesnt have any attributes.

So for this kind of XML what parser should I use to be able to save it into an ArrayList? And I only wanna list my OBJECT_TYPES nothing else. No prop and no params.

È stato utile?

Soluzione

This is the way

import java.util.ArrayList;

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

   public static void main(String argv[]) {
       final ArrayList<String> al=new ArrayList<String>();

    try {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

    boolean bfname = false;
    boolean blname = false;
    boolean bnname = false;
    boolean bsalary = false;

    public void startElement(String uri, String localName,String qName, 
                Attributes attributes) throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("OBJECT_TYPE")) {
            bfname = true;
        }



    }

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

        System.out.println("End Element :" + qName);

    }

    public void characters(char ch[], int start, int length) throws SAXException {

        if (bfname) {

            al.add(new String(ch, start, length));
            bfname = false;
        }



    }

     };

       saxParser.parse("C:\\Users\\Naren\\workspace\\Regex\\src\\test.xml", handler);
       System.out.println(al);

     } catch (Exception e) {
       e.printStackTrace();
     }

   }

}

output

[horse, cat, car]

Altri suggerimenti

The standard pattern for SAX parsing this kind of format would be

  • startElement
    • if tag name is OBJECT_TYPE then create a new buffer (e.g. StringBuilder) to gather character data.
  • characters
    • if there is an active buffer, append the current chunk of characters to that buffer
  • endElement
    • if the tag name is OBJECT_TYPE turn the buffer into a string and do whatever you need to do with it.

The parser will deliver the text content of elements to the characters method of your handler, but it is not guaranteed to give you the whole block of contiguous text in one single chunk, which is why you need to accumulate it in a buffer and do the processing at endElement.

This is how I solved it :

public void ParserForObjectTypes() throws SAXException, IOException,
            ParserConfigurationException {

        try {
            FileInputStream file = new FileInputStream(new File(
                    "xmlFiles/CoreDatamodel.xml"));

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();

            DocumentBuilder builder = builderFactory.newDocumentBuilder();

            Document xmlDocument = builder.parse(file);

            XPath xPath = XPathFactory.newInstance().newXPath();

            String expression = "//OBJECT_TYPE";
            NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(
                    xmlDocument, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {


                model.addElement(nodeList.item(i).getFirstChild()
                        .getNodeValue());

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top