简体   繁体   中英

How to remove an XML node searching by child node value using Nokogiri?

I need to delete from the following XML the Imovel Node with CodigoImovel == 6124-2 using Nokogiri Gem.

<?xml version="1.0" encoding="UTF-8"?>
<Carga xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Imoveis>
        <Imovel>
            <CodigoImovel>6124-2</CodigoImovel>
            <TipoImovel>Apartamento</TipoImovel>
            <SubTipoImovel>Apartamento Padrão</SubTipoImovel>
        </Imovel>
        <Imovel>
            <CodigoImovel>86765</CodigoImovel>
            <TipoImovel>Apartamento</TipoImovel>
            <SubTipoImovel>Apartamento Padrão</SubTipoImovel>
            <CategoriaImovel>Cobertura</CategoriaImovel>
        </Imovel>
        <Imovel>
            <CodigoImovel>981768</CodigoImovel>
            <TipoImovel>Casa</TipoImovel>
            <SubTipoImovel>Casa de Condomínio</SubTipoImovel>
            <CategoriaImovel>Térrea</CategoriaImovel>
        </Imovel>
        <Imovel>
            <CodigoImovel>357468</CodigoImovel>
            <TipoImovel>Casa</TipoImovel>
            <SubTipoImovel>Casa de Condomínio</SubTipoImovel>
            <CategoriaImovel>Térrea</CategoriaImovel>
        </Imovel>
        <Imovel>
            <CodigoImovel>587168</CodigoImovel>
            <TipoImovel>Comercial/Industrial</TipoImovel>
            <SubTipoImovel>Conjunto</SubTipoImovel>
            <CategoriaImovel>Comercial/Sala Padrão</CategoriaImovel>
        </Imovel>
    </Imoveis>
</Carga>

The XML code is in the xml_str variable and I parsed with this:

xml = Nokogiri::XML(xml_str)

This code creates correctly the XML structure with Nokogiri, but I don't know how find by element value and after how to remove it.

Previously I had an ID attribute in the Imovel element, like that:

<Imovel id="6124-2">......</Imovel>

And I am using this to remove:

xml.css('#'+imovel_id).remove

And it works fine. But the system that will receive this XML does not allow extra attributes in the Imovel node.

I appreciate any help. Thanks!

I solved the question with this code:

xml.xpath("//Carga//Imoveis//Imovel[CodigoImovel='"+re_code+"']").remove

The XPATH allows to search in specific node by value. This query returns the specific node. Then the job is to remove the node.

The accepted answer in this question helped me in the solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM