我在JAXB中做了简单的编组和解组,如何使用JAXB在我的xml中插入/删除/搜索元素。请提供代码段。
我的输入XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<comments>
<comment id="id-1">Text1</comment>
<comment id="id-2">Text2</comment>
<comment id="id-3">Text3</comment>
</comments>
java中的我的Mapping类
@XmlRootElement( name = "comments" )
public class CommentsNode {
List<CommentNode> comments;
@XmlElement( name = "comment" )
public void setComments(List<CommentNode> comments){
this.comments = comments;
}
public List<CommentNode> getComments(){
return this.comments;
}
}
@XmlRootElement( name = "comment" )
@XmlType(propOrder = { "id" })
public class CommentNode {
String id = null;
@XmlAttribute ( name = "id" )
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
}
unmarshall代码:
File file = new File("/Users/vignesh-1200/Desktop/JAXB/sample.xml");
//StreamSource s = new StreamSource(file);
JAXBContext jaxbContext = JAXBContext.newInstance(CommentsNode.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
CommentsNode commentsNode = (CommentsNode) jaxbUnmarshaller.unmarshal(file);
List<CommentNode> childrens = commentsNode.getComments();
if(childrens!=null){
for(int i=0,j=childrens.size();i<j;i++){
CommentNode child = childrens.get(i);
System.out.println(child.getId()+":"+child.getUserId());
}
}else{
System.out.println("Childrens Empty");
}
如何使用属性值在xml中获取特定元素。例如,id = 2。请帮助我。
答案 0 :(得分:1)
在Java 8中足够简单:
commentsNode.getComments().stream()
.filter(node -> node.getId() == 2)
.findFirst().get()