How do I use the value of an XML element when setting the path in the Java SimpleXML library?

前端 未结 3 1758
傲寒
傲寒 2021-01-21 10:25

I have the following XML:


  
version 15.0 &
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-21 10:56

    Using SimpleXML ver: 2.6.6. - without using the annotation @Element(name = "value") you can do the following:

    /**
     * User: alfasin
     * Date: 8/21/13
     */
    
    import org.simpleframework.xml.Element;
    import org.simpleframework.xml.Path;
    import org.simpleframework.xml.Root;
    import org.simpleframework.xml.Serializer;
    import org.simpleframework.xml.core.Persister;
    
    import java.io.File;
    
    @Root(name = "rdr", strict = false)
    public class SimpleXml {
        @Element
        @Path("details/detail[1]")
        private String name;
    
        @Element
        @Path("details/detail[1]")
        private String value;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getValue() {
            return value;
        }
    
        public void setValue(String value) {
            this.value = value;
        }
    
        public static void main(String...args) throws Exception {
            String fileName = "C:\\Users\\Nir\\IdeaProjects\\Play\\rdr.xml";
            Serializer serializer = new Persister();
            File source = new File(fileName);
    
            SimpleXml example = serializer.read(SimpleXml.class, source);
            System.out.println(example.getName());
            System.out.println(example.getValue());
        }
    
    }
    

    OUTPUT:

    version
    15.0
    

    However, according to the documentation, using XPATH requires that you'll name the variable with the same name that is used in the XML, alas, you can't have two class members sharing the same name ("name and "value"), which means that you cannot use XPATH unless you have only ONE detail object in the XML.

提交回复
热议问题