I am trying to parse cascaded types(not sure if this is the right term) from xml files.
What I mean by cascaded types is that the attribute ntype of an xml element could be any of the following ones.
<ntype A>
<ntype A:A1>
<ntype A:A2>
<ntype B>
<ntype B:B1>
<ntype B:B2>
...
This is similar to the layout specifications in the android xml files like android:layout_width,android:layout_height etc.,
The ntype decides the type of the xml file and based on that further processing of the data is done.
Currently the way I’m parsing this is by having all the ntypes in an enumerated datatype like this: (By removing the “:” from the ntype)
public static enum NType {
A,
AA1,
AA2,
B,
BB1,
BB2,
...
}
In the parser I do
NType nType = NType.valueof(attributes.getValue("ntype").replace(":","");
However, if a new ntype is added to the xml file and that type is not there in the enum the app crashes. I wanted to know if there is any better way of storing these cascaded types of data and how should I add a default behavior if the ntype doesn’t exist so that the app doesn’t crash.
Any help is appreciated.
PS: I am slightly less knowledgeable in theoretical computer science and I believe this is mostly a theoretical question as to which/what/how tools from programming language should be used.
Not sure if it will work as your question is a little abstract and I don’t know what your
ntypesare or what you need to do when processing the document. How about this…Rather than create your static enum, you could do a two-pass parsing operation and create a collection of some sort (perhaps a
List<String>although other collections may be more suitable).In short, I’d run a first pass and use the collection’s
contains(Object E)method to see if it already contains that ntype – if not then use theadd(Object E)method to add it. Do this for the whole xml document.Second pass, process the document as you need to but (assuming you want an int value representing the ntype) use the collections
indexOf(Object E)method.By parsing the document and compiling all of the
ntypeson the first pass, you’ll be dynamically ensuring that you know all of them without risk of coming across an unknownntype.