Jquery:从xml中删除特定节点并获取剩余的xml

时间:2015-03-28 21:23:40

标签: php jquery xml

下面是我的xml,我想删除完整的数据,包括 来自以下xml的<onward-solutions>

var xml=' 
   <search-result>
   <onward-solutions>
    <solution index="1">
    </solution>
    <solution index="2">
    </solution>
    <solution index="3">
    </solution>
    </onward-solutions>
    <return-solutions>
    <solution index="1">
    </solution>
    <solution index="2">
    </solution>
    <solution index="3">
    </solution>
    </return-solutions>
    </search-result>
';

以下是xml的估计输出:

<search-result>
<return-solutions>
<solution index="1">
</solution>
<solution index="2">
</solution>
<solution index="3">
</solution>
</return-solutions>
</search-result>

任何人都可以帮助我如何获得预期的结果吗?

1 个答案:

答案 0 :(得分:0)

如果您想使用jQuery,可以尝试以下方法:

// Convert the xml string to a jQuery object.
var $xml = $(xml);

// Manipulate the jQuery object.
$xml.children('onward-solutions').remove();

// Convert the jQuery object back to an xml string.
xml = $xml.wrap('<x></x>').parent().html();

jsfiddle

如果您的xml字符串在开头包含xml声明,请执行以下操作:

<!--?xml version="1.0" encoding="UTF-8"?-->

您可以使用以下内容:

// Parse the xml string into an XMLDocument and then create a jQuery object
// using the root element.
var $xml = $($.parseXML(xml).documentElement);

//  Manipulate the jQuery object.
$xml.children('onward-solutions').remove();

// Convert the jQuery object back to an xml string.
// Note: For some reason the .wrap() function does not work in this case,
//       so we use .appendTo() instead.
xml = $xml.appendTo('<x></x>').parent().html();

jsfiddle