Удаление узлов в XML

Я новичок в манипулировании xml и надеюсь, что смогу получить от вас некоторую помощь.

Моя внутренняя система выдает XML-файл со следующей структурой узлов.

<orders xmlns="http://www.foo.com/xml/impex/order/">
<order order-no="0000000000000303">
<order-date>2011-09-02T18:55:00.000Z</order-date>
<created-by>foo</created-by>
<original-order-no>0000000000000303</original-order-no>
<currency>USD</currency>
<customer-locale>default</customer-locale>
<affiliate-partner-name/>
<affiliate-partner-id/>
<invoice-no>00001422</invoice-no>
<customer>...</customer>
<customer-order-reference/>
<status>...</status>
<replace-code/>
<replace-description/>
<replacement-order-no/>
<replaced-order-no/>
<current-order-no>0000000000000303</current-order-no>
<cancel-code/>
<cancel-description/>
<product-lineitems>...</product-lineitems>
<giftcertificate-lineitems/>
<shipping-lineitems>...</shipping-lineitems>
<shipments>...</shipments>
<totals>...</totals>
<payments>
<payment>
<gift-certificate>
<custom-attributes>
<custom-attribute attribute-id="giftCard01Number">01000169466975</custom-attribute>
<custom-attribute attribute-id="giftCard01Value">10.00</custom-attribute>
<custom-attribute attribute-id="giftCard02Number">01100995910</custom-attribute>
<custom-attribute attribute-id="giftCard02Value">20.00</custom-attribute>
<custom-attribute attribute-id="giftCertificateType">card</custom-attribute>
</custom-attributes>
</gift-certificate>
<amount>10.00</amount>
<processor-id>BARNEYS_GIFT_CARD</processor-id>
<transaction-id>0000000000000303</transaction-id>
</payment>
<payment>
<gift-certificate>
<custom-attributes>
<custom-attribute attribute-id="giftCard02Number">01100995910</custom-attribute>
<custom-attribute attribute-id="giftCard02Value">20.00</custom-attribute>
<custom-attribute attribute-id="giftCertificateType">card</custom-attribute>
</custom-attributes>
</gift-certificate>
<processor-id>BARNEYS_GIFT_CARD</processor-id>
</payment>
<payment>
<credit-card>...</credit-card>
<amount>35.33</amount>
<processor-id>VCOMMERCE_CREDIT</processor-id>
<transaction-id>0000000000000303</transaction-id>
<custom-attributes>...</custom-attributes>
</payment>
</payments>
<remoteHost/>
<external-order-no/>
<external-order-status/>
<external-order-text/>
<custom-attributes>...</custom-attributes>
</order>
</orders>

Теперь нужно изменить порядок Node. Данные, которые необходимо сохранить, - это первый и последний платежные узлы. Любой другой узел, который находится посередине, может быть удален или удален. Есть ли способ сделать это с помощью E4x?

Спасибо за вашу помощь. Берто


person Berto    schedule 05.09.2011    source источник
comment
Что остаётся? Вы имеете в виду переименование? Удаление?   -  person Oded    schedule 05.09.2011
comment
Зачем вам нужно использовать E4X? Вы упомянули, что XML-файл создается на серверной стороне, поэтому разве вы не можете использовать внутренний язык / технологию для управления XML-файлом?   -  person clarkb86    schedule 06.09.2011
comment
Что делать, если есть 2 платежных узла? Вы удаляете первым и последним? В порядке слов вы удалите их обоих?   -  person Paul Grime    schedule 06.09.2011


Ответы (1)


Не уверен насчет E4X, но использую Rhino, Envjs и jQuery:

Запустить Rhino:

java -jar js.jar -opt -1

Теперь вы должны быть в командной строке Rhino.

Загрузите несколько библиотек (я не рекомендую загружать из Интернета, но для целей примера), прочтите файл заказов, проанализируйте в xml, удалите платежи, затем распечатайте результат ...

load("http://www.envjs.com/dist/env.rhino.1.2.js")
load("https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js")
load("../rhino-scripts/removeFirstAndLastPayments.js")
xmlstr = readFile("../rhino-scripts/orders.xml")
xml = $.parseXML(xmlstr)
removeFirstAndLastPayments(xml)
new XMLSerializer().serializeToString(xml)

Где removeFirstAndLastPayments определяется как:

function removeFirstAndLastPayments(root) {
    $(root).find("orders order").each(function (orderIdx, order) {
        var payments = $(order).find("payment");
        if (payments.length > 2) {
            // only remove first and last if there are more than 2 payments
            payments.first().remove();
            payments.last().remove();
        }
    });
}
person Paul Grime    schedule 05.09.2011
comment
Пол, спасибо, что вернулся ко мне. Я дам ему попробовать. и дайте вам знать. Ура Берто - person Berto; 06.09.2011