java xml annotation get field with namespace, value

后端 未结 2 359
轮回少年
轮回少年 2020-12-21 18:32

I\'m working on a project that has no schema and I have to parsing the xml response manually. My problem is i can\'t get some value using the xml annotation.

For exa

2条回答
  •  天涯浪人
    2020-12-21 19:13

    JAXB and other XML processors that are capable of processing XML Schema are going to treat everything before a : as a namespace prefix. If the colon is then you can do the following.

    Java Model

    You need to specify that your element name contains the : character.

    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class ResponseData {
    
        @XmlElement(name = "autn:numhits")
        private String numhits;
    
        private String totalhits;
    
    }
    

    Demo

    import javax.xml.bind.*;
    import javax.xml.parsers.*;
    import org.xml.sax.XMLReader;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            // Create a SAXParser that is not namespace aware
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
    
            // Create the JAXBContext
            JAXBContext jc = JAXBContext.newInstance(AutonomyResponse.class);
    
            // Instead of Unmarshaller we will use an UnmarshallerHandler
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler();
    
            // Do a SAX parse with the UnmarshallerHanlder as the ContentHandler
            xr.setContentHandler(unmarshallerHandler);
            xr.parse("src/forum20062536/input.xml");
    
            // Get the result of the unmarshal
            AutonomyResponse autonomyResponse = (AutonomyResponse) unmarshallerHandler.getResult();
    
            // Marshal the object back to XML
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(autonomyResponse, System.out);
        }
    
    }
    

提交回复
热议问题