Reputation: 1395
There is xml in String format like this:
<Users>
<User>
<name>Alex</name>
...other info
</User>
<User>
<name>Natasha</name>
...other info
</User>
</Users>
how to split String like this to array of String's?
My common task is, get input xml, split on elemens and every element serialize and save in database separately. SO, for my task SAX, only Pattern and Matcher may be.
Upvotes: 0
Views: 229
Reputation: 11
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
}
Upvotes: 1
Reputation: 540
Sax parser is my favorite, you can try it : Oracle
This is the sample xml parse code example from: tutorialspoint.com
Upvotes: 1