我有一个类似的xml:
<document>
<paragraph>
<a>
<b>
<c>
<d>text1</d>
</c>
</b>
</a>
</paragraph>
<paragraph>
<a>
<b>
<c>
<d>text2</d>
</c>
</b>
</a>
</paragraph>
</document>
显然还有更多的段落,等等。
使用cheerio (jquery的语法也适用),我想包装d
元素,直到它只有paragraph
作为父元素。
<document>
<paragraph>
<d>text1</d>
</paragraph>
<paragraph>
<d>text2</d>
</paragraph>
</document>
我想过在元素上使用.unwrap()
命令3次。但我不能保证在d
和paragraph
之间的一些xml中,父元素的数量可能会更少或更多。
发布于 2017-12-05 02:26:03
不确定这是否适用于您的环境,但是,我认为您可以使用idea:
$('d').each(function() {
cloned=$(this).clone();
$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();
});
所以,克隆元素,将其放在段落内,删除所有parentsUntil()
段落...
演示:
$('d').each(function() {
cloned=$(this).clone();
$(this).closest('paragraph').append(cloned);
$(this).parentsUntil($('paragraph')).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<document>
<paragraph>
<a>
<b>
<c>
<d>text1</d>
</c>
</b>
</a>
</paragraph>
<paragraph>
<a>
<b>
<c>
<d>text2</d>
</c>
</b>
</a>
</paragraph>
</document>
发布于 2017-12-05 02:25:56
这是我的解决方案。我使用for循环克隆<d>
元素,然后将其重写为段落元素。
JS
$(document).ready(function(){
var i = $('d').length;
for(x=i--;x>=0;x--){
var c = $('d').eq(x).clone();
$('d').eq(x).parents('paragraph').html(c);
}
});
https://stackoverflow.com/questions/47639344
复制相似问题