View Javadoc
1   /*
2    * Copyright (c) 2008, The JUNG Authors
3    *
4    * All rights reserved.
5    *
6    * This software is open-source under the BSD license; see either
7    * "license.txt" or
8    * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
9    */
10  
11  package edu.uci.ics.jung.io.graphml.parser;
12  
13  import java.util.Stack;
14  
15  import javax.xml.stream.XMLEventReader;
16  import javax.xml.stream.events.StartElement;
17  import javax.xml.stream.events.XMLEvent;
18  
19  import edu.uci.ics.jung.io.GraphIOException;
20  import edu.uci.ics.jung.io.graphml.ExceptionConverter;
21  
22  /**
23   * Skips an entire unknown subtree of the XML
24   *
25   * @author Nathan Mittler - nathan.mittler@gmail.com
26   */
27  public class UnknownElementParser implements ElementParser {
28  
29      /**
30       * Skips an entire subtree starting with the provided unknown element.
31       * 
32       * @param xmlEventReader
33       *            the event reader
34       * @param start
35       *            the unknown element to be skipped.
36       * @return null
37       */
38      public Object parse(XMLEventReader xmlEventReader, StartElement start)
39              throws GraphIOException {
40  
41          try {
42              Stack<String> skippedElements = new Stack<String>();
43              skippedElements.add(start.getName().getLocalPart());
44  
45              while (xmlEventReader.hasNext()) {
46  
47                  XMLEvent event = xmlEventReader.nextEvent();
48                  if (event.isStartElement()) {
49  
50                      String name = event.asStartElement().getName()
51                              .getLocalPart();
52  
53                      // Push the name of the unknown element.
54                      skippedElements.push(name);
55                  }
56                  if (event.isEndElement()) {
57  
58                      String name = event.asEndElement().getName()
59                              .getLocalPart();
60  
61                      if (skippedElements.size() == 0
62                              || !skippedElements.peek().equals(name)) {
63                          throw new GraphIOException(
64                                  "Failed parsing GraphML document - startTag/endTag mismatch");
65                      }
66  
67                      // Pop the stack.
68                      skippedElements.pop();                        
69                      if( skippedElements.isEmpty() ) {
70                          break;
71                      }
72                  }
73              }
74  
75              return null;
76  
77          } catch (Exception e) {
78              ExceptionConverter.convert(e);
79          }
80  
81          return null;
82      }
83  }