Assuming you want an output like
names[] = {"Alex", "Natasha"};
from the XML file:
<Users>
<User>
<name>Alex</name>
<city>New York</city>
</User>
<User>
<name>Natasha</name>
<city>New Jersey</city>
</User>
</Users>
You can use a JacksonXML parser to get the names of all the users.
I have used a Users class for RootElement
@JacksonXmlRootElement(localName = "Users")
public class Users {
@JacksonXmlProperty(isAttribute=false, localName="User")
@JacksonXmlElementWrapper(useWrapping = false)
private List<User> user;
public List<User> getUsers() {
return user;
}
public void setUsers(List<User> users) {
this.user = users;
}
}
and a User class for the inner user-block
public class User {
@JacksonXmlProperty(isAttribute=false, localName="name")
private String name;
@JacksonXmlProperty(isAttribute=false, localName="city")
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
and then read the XML file as:
public static void main(String[] args) throws XMLStreamException, IOException {
XmlMapper xmlMapper = new XmlMapper();
Users users = xmlMapper.readValue(new File("yourFileName"), Users.class);
Object[] names = users.getUsers()
.stream()
.map(u -> u.getName())
.collect(Collectors.toList())
.toArray();
//You may have to cast the names to String
}