有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从xml中读取未知元素

如果有这样的XML文件:

<List>
    <ListItem>
        <Element1>foo</Element1>
    </ListItem>
    <ListItem>
        <Element2>another foo</Element2>
    </ListItem>
    <ListItem>
        <Element3>foo foo</Element3>
    </ListItem>
    <ListItem>
        <Element4>foooo</Element4>
    </ListItem>
    <ListItem>
        <Element5>foo five</Element5>
    </ListItem>
</List>

如何读取名称总是不同的元素?<ListItem>标记始终相同,但元素的名称始终不同

我被困在这一点上:

@Root(name = "ListItem")
public class ListItem
{
    @Element(name = ?????)
    String Element;
}

最后我想这样使用它:

...

    @ElementList(name = "List")
    List<ListItem> Items;

...

问候


共 (1) 个答案

  1. # 1 楼答案

    如果元素变化那么大,您将不得不手动执行一些工作-但是,这并不多:

    1. 实现一个Converter,例如ListItemConverter
    2. 通过@Convert注释启用它
    3. 为序列化程序设置AnnotationStrategy

    @Root(name = "List")
    public class ExampleList
    {
        @ElementList(inline = true)
        private List<ListItem> elements;
    
        /* ... */
    
    
        @Root(name = "ListItem")
        @Convert(ListItemConverter.class)
        public static class ListItem
        {
            private final String text;
    
    
            public ListItem(String text)
            {
                this.text = text;
            }
    
            /* ... */
        }
    
        static class ListItemConverter implements Converter<ListItem>
        {
            @Override
            public ListItem read(InputNode node) throws Exception
            {
                final InputNode child = node.getNext();
    
                if( child != null )
                {
                    /*
                     * If you need the 'Element*' too:
                     * child.getName()
                     */
                    return new ListItem(child.getValue());
                }
    
                return null;
            }
    
    
            @Override
            public void write(OutputNode node, ListItem value) throws Exception
            {
                // Implement if you also need to write ListItem's
                throw new UnsupportedOperationException("Not supported yet.");
            }
        }
    
    }
    

    不要忘记设置AnnotationStrategy,否则@Convert将无法工作:

    Serializer ser = new Persister(new AnnotationStrategy());
    // ...