-
xml parser
I've never done this sort of parsing before and I'm having trouble getting it to work for my purposes. I'm using DOM parser to parse an xml file and then I want to retrieve all the values under "OperatingParameters." My code so far ... and the section of the xml file I'm interested in follow. I know the way I've done is wrong. Should I be using attributes instead...?
Code:
import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XMLhandler {
private File xmlFile;
private Document doc;
public XMLhandler(File file) { xmlFile = file; }
public void parse() {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(xmlFile);
} catch (Exception e) { e.printStackTrace(); }
}
public String[] getElements(String tagName) {
String[] s = new String[100];
Element element = doc.getDocumentElement();
NodeList list = element.getElementsByTagName(tagName);
for (int i = 0; i < element.getLength(); i++) {
Element item = (Element) list.item(i);
}
return s;
}
}
Code:
<OperatingParameters
Mode="Mass sweep"
Focus1="-20"
Focus2="-20"
ElectronEnergy="70"
FilamentEmission="2.0"
AutoZero="Off"
ScanMode="Sweep"
Filament="1"
PressureUnits="Torr"
EnableElectronMultiplier="0"
MultiplierVoltage="1110"
/>
-
Re: xml parser
What happens when you use that code?
What do you see, and what do you want to see?
-
Re: xml parser
Well, the NodeList I get back if, say, I were to print it contains only one element "OperatingParameters." what I want to be able to do is get a list of all the individual elements that follow OperatingParameters in the xml code I posted.
-
Re: xml parser
As you guessed, though, there are no elements.
There are, however, attributes.
You could use getAttributes() on the Element and cycle through the Map that's returned?
-
Re: xml parser
so this method should return all attributes in the element?
-
Re: xml parser
Yes.
Here's the API for it (which I forgot to link to earlier).
-
Re: xml parser
hmm...
If I insert this into my code:
Element element = doc.getDocumentElement();
NamedNodeMap map = element.getAttributes();
System.out.println(map.getLength());
map.getLength(); is zero
-
Re: xml parser
Because your document element (which is the root of your XML) probably doesn't have any attributes?
I thought you were going to do this on the elements in your NodeList?