【发布时间】:2015-04-05 06:31:12
【问题描述】:
我在 JAXB 中进行了简单的编组和解组,如何使用 JAXB 在我的 xml 中插入/删除/搜索元素。请提供代码sn-p。
我的输入 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 中的映射类
@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;
}
}
解组代码:
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。请帮助我。
【问题讨论】:
标签: java xml-parsing jaxb