michael aboah
michael aboah

Reputation: 11

Trying to iterate over very similar Elements in an XML file. NOTE XML file is attribute less

Hullo, I have a question about xml and java. I have a weird XML file with no attributes and only Elements, im trying to zero in on a specific Element Stack, and then iterate over all of the similar element stacks.

  <InstrumentData>
    <Action>Entire Plot</Action>
    <AppStamp>Vectorworks</AppStamp>
    <VWVersion>2502</VWVersion>
    <VWBuild>523565</VWBuild>
    <AutoRot2D>false</AutoRot2D>
    <UID_1505_1_1_0_0>   ---- This is the part I care about, there are about 1000+ of these and they all vary slightly after the "UID_"---
      <Action>Update</Action>
      <TimeStamp>20200427192323</TimeStamp>
      <AppStamp>Vectorworks</AppStamp>
      <UID>1505.1.1.0.0</UID>
    </UID_1505_1_1_0_0>

I am using dom4j as the xml parser and I dont have any issues spitting out all of the data I just want to zero in on the XML path.

This is the code so far:

public class Unmarshal {
    
    public Unmarshal() {
        File file = new File("/Users/michaelaboah/Desktop/LIHN 1.11.18 v2020.xml");
        SAXReader reader = new SAXReader();
        try {
            Document doc = reader.read(file);       
            Element ele = doc.getRootElement();
            Iterator<Element> it = ele.elementIterator();
            Iterator<Node> nodeIt = ele.nodeIterator();
            
            while(it.hasNext()) {
                Element test2 = (Element) it.next();
                List<Element> eleList = ele.elements();
                
                for(Element elementsIt : eleList) {
                    System.out.println(elementsIt.selectSingleNode("/SLData/InstrumentData").getStringValue());
                        //This spits out everything under the Instrument Data branch
                        //All of that data is very large
                    
                    System.out.println(elementsIt.selectSingleNode("/SLData/InstrumentData/UID_1505_1_1_0_0").getStringValue());
                        //This spits out everything under the UID branch
                }
            }
                    
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Also, I know there are some unused data types and variables there was a lot of testing

Upvotes: 1

Views: 174

Answers (1)

Waelmio
Waelmio

Reputation: 151

I think your answer is:

elementsIt.selectSingleNode("/SLData/InstrumentData/*[starts-with(local-name(), 'UID_')]").getStringValue()

I used this post to find this XPath and it works with the few xml lines you gave.

Upvotes: 1

Related Questions