0

I know how to parse an XML file that has one of each field e.g. Name, ID, Age by getting sub-elements using DOM parser and putting them into a Nodelist.

However I don't know how to parse and store data from an XML file with repeated fields. For example, each facility has more than one item, and it has more than one "link" with a distance to each link, for instance Seattle has a link to Fargo in this XML file, with a distance of 1426.

How would I approach parsing for the items and links? I can't simply match by the substring item, since I have multiple items.I don't know if it's appropriate to use a Nodelist, so I'm not sure which kind of data structure to use.

I've googled XML parsing in Java and I'm still confused, and I don't know what kind of data structure to use to store all this information.

<Facility>
    <Name>Seattle, WA</Name>
    <ProcessingRate>8</ProcessingRate>
    <ProcessingCost>300</ProcessingCost>
    <Link>
        <Name>Fargo, ND</Name>
        <Distance>1426</Distance>
    </Link>
    <Link>
        <Name>San Francisco, CA</Name>
        <Distance>808</Distance>
    </Link>
    <Item>
        <Id>ABC123</Id>
        <Quantity>45</Quantity>
    </Item>
    <Item>
        <Id>JBL3100</Id>
        <Quantity>52</Quantity>
    </Item>
    <Item>
        <Id>PL132-C</Id>
        <Quantity>54</Quantity>
    </Item>
    <Item>
        <Id>PU238</Id>
        <Quantity>60</Quantity>
    </Item>
</Facility>

<Facility>
J. Don
  • 1
  • 2
  • Possible duplicate of [Convert XML file into an XML object having a List](http://stackoverflow.com/questions/13987708/convert-xml-file-into-an-xml-object-having-a-list) – tima May 07 '17 at 02:58

2 Answers2

0

You can read this xml file to a class object like this:

class Facility {
    String Name;
    String ProcessingRate;
    String ProcessingCost;
    List<ChildObject> links;
    List<ChildObject> items;
}

class ChildObject {
    String name;
    String value;
    String type;
}
TuyenNTA
  • 1,194
  • 1
  • 11
  • 19
  • How would I parse it though? In the person example I gave for example I would parse using something like this: an array list of names, then getElementByTagName("ID"), getElementByTagName("Age") and so on. – J. Don May 07 '17 at 00:31
  • You can do it by yourself. Just read the xml and put the values to the equivalent fields in this object. You can refer to [this post](https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/) for detail about reading xml. Then just mapping to above object class – TuyenNTA May 07 '17 at 00:37
0

@JacksonXmlElementWrapper(useWrapping = false) this annotation helped me

    @JsonProperty("Events")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Events> events;
Boris Mitioglov
  • 1,092
  • 4
  • 16
  • 32