如何使用XmlStarlet将标签添加到XML文档而不重复

时间:2019-06-06 15:10:22

标签: xml xpath xml-parsing xmlstarlet

我正试图在我的server.xml tomcat文档中添加一个'Listener'标签。但是当我尝试添加它时,它就会成倍增加。

当我尝试以下操作时,它会放置多个标签,并且添加的属性会附加到每个侦听器标签上。

@Component
public class ValidationDatasProcessor implements Processor {

    @Autowired ObjectMapper objectMapper;

    @Autowired ClientRepository clientRepository;

    @Override
    public void process(Exchange exchange) throws Exception {
        String clientString = exchange.getIn().getBody(String.class);
        Client client = objectMapper.readValue(clientString, Client.class);
        clientRepository.saveAndFlush(client)
        exchange.setOut(generateOutMessage(client, exchange.getContext()));
    }

    Message generateOutMessage(Client client, CamelContext camelContext) throws JsonProcessingException {
        DefaultMessage outMessage = new DefaultMessage(camelContext);
        outMessage.setBody(objectMapper.writeValueAsString(client), String.class);
        return outMessage;
    }
}

@Component
public class ClientProcessor implements Processor {

    @Autowired ObjectMapper objectMapper;

    @Autowired ClientRepository clientRepository;

    ....

    @Override
    public void process(Exchange exchange) throws Exception {
        String clientString = exchange.getIn().getBody(String.class);
        Client client = objectMapper.readValue(clientString, Client.class);
        client.setAccessDate(LocalDateTime.now);
        clientRepository.saveAndFlush(client)
        exchange.setOut(generateOutMessage(client, exchange.getContext()));
    }

    Message generateOutMessage(Client client, CamelContext camelContext) throws JsonProcessingException {
        DefaultMessage outMessage = new DefaultMessage(camelContext);
        outMessage.setBody(objectMapper.writeValueAsString(client), String.class);
        return outMessage;
    }
}

文档

xmlstarlet edit --omit-decl \
--insert "/Server" --type elem --name "Listener" \
--subnode "/Server/Listener" --type attr -name "className" --value "org.jboss.modcluster.container.tomcat.ModClusterListener" \
server.xml > temp.xml

我想要的是添加一个“ Listener”标签,并且该标签应具有modcluster类名。

1 个答案:

答案 0 :(得分:0)

这实际上对我有用:

xmlstarlet edit --omit-decl \
--append "Server/Listener[5]" --type elem --name "Listener" \
--subnode "/Server/Listener[6]" --type attr -name "className" --value "org.jboss.modcluster.container.tomcat.ModClusterListener" \
server.xml > temp.xml