Pavel Janicek
Pavel Janicek

Reputation: 14738

How to read xml file with attributes in java?

I am aware of SO question Failing to get element values using Element.getAttribute() but because I am java begginer, I have additional questions. What I am trying to build is simple application, which will read XML file and then compare it against "golden master." My problem is:

Example of file:

  <DocumentIdentification v="Unique_ID"/>
  <DocumentVersion v="1"/>
  <DocumentType v="P81"/>
  <SenderIdentification v="TEST-001--123456" codingScheme="A01"/>
  <CreationDateTime v="2012-10-15T13:00:00Z"/>
  <InArea v="10STS-TST------W" codingScheme="A01"/>
  <OutArea v="10YWT-AYXOP01--8" codingScheme="A01"/>
  <TimeSeries>
<Period>
 <TimeInterval v="2012-10-14T22:00Z/2012-10-15T22:00Z"/>
   <Resolution v="PT15M"/>
        <Interval>
            <Pos v="1"/>
            <Qty v="500"/>
        </Interval>
        <Interval>
            <Pos v="2"/>
            <Qty v="500"/>
        </Interval>
        <Interval>
            <Pos v="3"/>
                            <Qty v="452"/>
                    </Interval>
                     ...
                     ...
                    <Interval>
            <Pos v="96"/>
                            <Qty v="891"/>
                    </Interval>
               </Period>   
        </TimeSeries>

Applying solution from the question mentioned above does not get me much further... I realised that I can cast attributes to NamedNodeMap but I dont know how to iterate through it programatically

Yes, I know it sounds much like "do my homework" but what I really need is at least small kick to butt, moving me in correct direction. Thanks for help

Upvotes: 0

Views: 498

Answers (1)

Andreas Dolk
Andreas Dolk

Reputation: 114767

The method item(int index) should help iterating through the attributes:

NamedNodeMap map = getItFromSomeWhere();
int i = 0;
while ((Node node = map.item(i++)) != null) {
   // node is ith node in the named map
}

Upvotes: 1

Related Questions