Using JAXB to extract inner text of XML element

前端 未结 2 1001
名媛妹妹
名媛妹妹 2020-12-03 22:20

Problem

Given the following XML configuration file:

JET 5 <
2条回答
  •  生来不讨喜
    2020-12-03 22:28

    You can use the @XmlAnyElement annotation as described by bmargulies. To map to the object model in your question you can leverage a DOMHandler.

    Main

    import javax.xml.bind.annotation.*;
    
    @XmlRootElement(name="main")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Main {
    
        private String name;
    
        private Integer maxInstances;
    
        @XmlAnyElement(value=ParameterHandler.class)
        private String parameters;
    
    }
    

    ParameterHandler

    import java.io.*;
    import javax.xml.bind.ValidationEventHandler;
    import javax.xml.bind.annotation.DomHandler;
    import javax.xml.transform.Source;
    import javax.xml.transform.stream.*;
    
    public class ParameterHandler implements DomHandler {
    
        private static final String PARAMETERS_START_TAG = "";
        private static final String PARAMETERS_END_TAG = "";
        private StringWriter xmlWriter = new StringWriter(); 
    
        public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
            return new StreamResult(xmlWriter);
        }
    
        public String getElement(StreamResult rt) {
            String xml = rt.getWriter().toString();
            int beginIndex = xml.indexOf(PARAMETERS_START_TAG) + PARAMETERS_START_TAG.length();
            int endIndex = xml.indexOf(PARAMETERS_END_TAG);
            return xml.substring(beginIndex, endIndex);
        }
    
        public Source marshal(String n, ValidationEventHandler errorHandler) {
            try {
                String xml = PARAMETERS_START_TAG + n.trim() + PARAMETERS_END_TAG;
                StringReader xmlReader = new StringReader(xml);
                return new StreamSource(xmlReader);
            } catch(Exception e) {
                throw new RuntimeException(e);
            }
        }
    
    }
    

    Demo

    import java.io.File;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception  {
            JAXBContext jc = JAXBContext.newInstance(Main.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Main main = (Main) unmarshaller.unmarshal(new File("input.xml"));
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(main, System.out);
        }
    
    }
    

提交回复
热议问题