【问题标题】:XML Element insert/delete/search using JAXB使用 JAXB 插入/删除/搜索 XML 元素
【发布时间】: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


    【解决方案1】:

    在 Java 8 中足够简单:

    commentsNode.getComments().stream()
        .filter(node -> node.getId() == 2)
        .findFirst().get()
    

    【讨论】:

    • 感谢艺术。有没有可能在 java 6&7 中工作或者我应该使用 DOM 处理?
    猜你喜欢
    • 2010-11-19
    • 2011-07-08
    • 1970-01-01
    • 2016-08-24
    • 2014-01-19
    • 1970-01-01
    • 2011-10-14
    • 2020-09-30
    • 1970-01-01
    相关资源
    最近更新 更多