How do you continue parsing even when expected elements are missing from xml file
Hi,
I have an XML file that can have a varying structure. For example in the chunk below the <subtrade> element has a subelement called <creditCurveFull>. However, <creditCurveFull> may be missing from the next <subtrade> element and reappear in the next <subtrade> element and so on.
Currently, my code just bombs out if it does not see the element that it is expecting to parse i.e. <creditCurveFull>. How do I deal with this so that my code continues to parse the rest of the document even if the elements that it is expecting to see are missing?
First, the text file that you posted shows code for walking the DOM tree so apparently the XML data has already been parsed and loaded into the DOM tree.
Just have your code check for the presence of the optional child element. If it's there then process it. If not then move on.
You may also want to organize your code so that each XML element produces a Java object.
In pseudo-code, something like ...
Code:
if (element.name == "book")
{
Book b = new book(element);
container.add(b);
}
In this example, the constructor initializes itself from the XML element. Any child elements would be handled inside the constructor which would do nothing more than pass the child element to another constructor ...
Code:
class Book
{
Book(Element element)
{
// grab attributes, store values.
// iterate child elements.
if ( child.name == "chapter" )
{
Chapter chap = new Chapter(child);
chapters.add(chap);
}
}
// and so on.
-rick
Last edited by rfmobile; October 14th, 2003 at 09:04 AM.
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.