How to create java model class to read xml file

198 views Asked by At

I am new to xml parsing and currently I have an xml file that I am trying to read through XmlMapper in a junit test case. But when I run the test, there is no error obtained but a null value for the file. I have the following Xml file -

<?xml version="1.0" encoding="ISO-8859-1"?>
<Root version="1.0">
    </Header>
    <Value line="1">
        <Id> 20868PW </Id>
        <Price> 7 </Price>
     </Item>
</Root>

Below is the code for reading the xml file-

private MyResponse getMockResponse() throws IOException {
 XmlMapper xmlMapper = new XmlMapper();
 File file = new File("src/test/MockedFile.xml");
 return xmlMapper.readValue(file, MyResponse.class);
}

MyResponse.java

public class MyResponse {
  @XmlElement(name="Root")
  private RootResponse root;
}

RootResponse.java

@XmlRootElement(name="Root")

public class RootResponse {
 @XmlElement(name="Value")
 private List<Value> value;
 @XmlElement(name="Header")
 private List<Header> header;
 @XmlAttribute
 private String version;

Is there something missing in my model class because of which the file is not read correctly and returns root = null?

2

There are 2 answers

1
Peng On

which xml parse library you used ? Not sure that it could slove the first line which is <?xml version="1.0" encoding="ISO-8859-1"?> , as suggestion , you can try to rm the first line of xml file , if it work , Obviously , you can change your xmp parse library.

0
Vidz Here On

Your xml is invalid.

  1. This is invalid tag : </Header>
  2. Correct way to write empty tag is : <Header/>
  3. Its a good practice to validate xml on an online parser like https://jsonformatter.org/xml-parser