1. Member
Join Date
Nov 2010
Posts
28
Rep Power
0

## xml parser (2)

My second post on the topic, I've created a class that will handle xml files for a larger project I am working on. The parse method I have been working on has been working fine. So in this method
Java Code:
doc
is a private
Java Code:
Document
variable that has already been parsed. What I'm looking to do is get each one of these attributes in the list, which I have managed to do. However, they are ordered differently in the list than they are in the xml file I read them from. It just seems to be a random order, which isn't good since eventually I'm looking to take the attributes and use them to populate some fields. Is there any way around this? One way I thought of was to get each attribute individually, but how would I do that if the Node api includes a getAtributtes method but not getAttribute...?

Java Code:
public String[] getValues(String tagName, int amount) {
String[] s1 = new String[2];
String[] s2 = new String[100];

doc.normalizeDocument();
Element rootElement = doc.getDocumentElement();
NodeList subElement = rootElement.getElementsByTagName(tagName);
Node element = subElement.item(0);

NamedNodeMap attributes = element.getAttributes();

for(int i = 0; i < amount; i++) {
s1 = (attributes.item(i).toString()).split("\"");
s2[i] = (s1[1]);
}

return s2;
}
xml code concerned:

XML Code:
<?xml version="1.0" encoding="us-ascii"?>
<ConfigurationData>
<CommunicationParameters
Port="COM1"
Baud="115200"
PacketFrequency="5.0"
PacketTimeout="1.0"
CommunicationsType="1"
UserFrequency="5.0"
UserTimeout="1.0"
NamedPort=""
/>

<ConfigurationParameters
Filename="C:\Documents and Settings\Tim Cowen.EXTORR-TIM.000\Desktop\shipped\in progress\sn4118_Repair\sn4118_Repair_factory_cal.cfg"
Description="Air + PTA"
TimeStamp="07d9000600010008000b0035003601e8"
DateTime="6/8/2009 11:53:54 AM"
Caption="4118 Repair"
Serial="0"
Model="0"
/>

<ScanParameters
ScanSpeed="144"
LowMass="1"
HighMass="110"
SamplesPerAMU="10"
/>

2. Moderator
Join Date
Apr 2009
Posts
12,425
Rep Power
21

## Re: xml parser (2)

You want a Map<String, String> to map the attribute name to it's value.
Return that, then the calling method can turn that into an appropriate object (eg a CommunicationParameters object, or a ConfigurationParameters object).

3. Member
Join Date
Nov 2010
Posts
28
Rep Power
0

## Re: xml parser (2)

Just to make sure, I'm assuming the attribute name is, for example, "SamplesPerAMU" ?

4. Moderator
Join Date
Apr 2009
Posts
12,425
Rep Power
21

## Re: xml parser (2)

Yep.
So (for that element) you'd have a map containing:
"ScanSpeed" -> "144"
"LowMass" -> "1"
"HighMass" -> "110"
"SamplesPerAMU" -> "10"

Since you know the 'tagName' (ie the class that this represents) you could pass this into a suitable class constructor or factory method.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•