Y
Y
yosiaproger2022-03-30 11:07:10
Java
yosiaproger, 2022-03-30 11:07:10

How to add "@" prefix to attribute of xml tag when converting to json?

There is a code that receives an xml stream, translates it into json and returns a json string

public static String xmlToJson(InputStream inputStream) {
        try {
            InputFactoryImpl inputFactory = new InputFactoryImpl();
            inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);

            OutputFactoryImpl outputFactory = new OutputFactoryImpl();
            outputFactory.setProperty(XMLStreamProperties.XSP_NAMESPACE_AWARE, Boolean.FALSE);

            XmlMapper xmlMapper = new XmlMapper(new XmlFactory(inputFactory,outputFactory), new JacksonXmlModule());
            xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);

            JsonNode node = xmlMapper.readTree(inputStream);
            ObjectMapper jsonMapper = new ObjectMapper();
            return jsonMapper.writeValueAsString(node);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


The problem is that when a tag in xml has an attribute (testAttr),
62440e58c769d710962161.png
62440ee24256f518246839.png
then the final json looks like this, which is not very convenient. I would like to add the @ prefix to the attribute to get @testAttr. I saw this possibility in many online xml -> json converters, but I don’t know how to do it using jackson .. And yes, xml will come in the form of a stream, so the option using any annotations from jackson is not suitable

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question