JAXB mixed content list contains newline characters

后端 未结 1 1463
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 02:57

I was hoping that you might be able to help me with a problem that I\'m facing regarding JAXB.

I have the following XML file:


    

        
1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 03:16

    Why It's Happening

    White space content in an element that has mixed context is treated as significant.

    How to Fix It

    You could use JAXB with StAX to support this use case. With StAX you can create a filtered XMLStreamReader so that any character strings that only contain white space are not reported as events. Below is an example of how you could implement it.

    import javax.xml.bind.*;
    import javax.xml.stream.*;
    import javax.xml.transform.stream.StreamSource;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Root.class);
    
            XMLInputFactory xif = XMLInputFactory.newFactory();
            XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/forum22284324/input.xml"));
            xsr = xif.createFilteredReader(xsr, new StreamFilter() {
    
                @Override
                public boolean accept(XMLStreamReader reader) {
                    if(reader.getEventType() == XMLStreamReader.CHARACTERS) {
                        return reader.getText().trim().length() > 0;
                    } 
                    return true;
                }
    
            });
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            Root root = (Root) unmarshaller.unmarshal(xsr);
        }
    
    }
    

    0 讨论(0)
提交回复
热议问题