提问人:Addy 提问时间:11/16/2018 最后编辑:Addy 更新时间:11/16/2018 访问量:61
解析 xml 以获取两个节点之间的所有节点
Parsing xml to get the all nodes between two nodes
问:
嗨,我有一个如下的xml:
> <body>
> <p>
>
> <xxx>
> <txt>{{<txt>
> </xxx>
> <Err type="Start"/>
> <xxx>
> <txt>f</txt>
> </xxx>
> <xxx>
> <txt>irst_name</txt>
> </xxx>
> <Err type="End"/>
> <xxx>
> <txt>}}</txt>
> </xxx>
> <p> </body>
所以我试图让一切介于
<Err type="Start"/> .... <Err type="End"/>
然后提取 txt 节点值以获得“firstName”的输出
这是我到目前为止所拥有的,但在这之后有点迷茫,请帮忙。
xml = $(mainXMl).find('p')
$(xml).each(function(wPrgs){
var parentEle = $(xml[wPrgs]).find('Err')
$(parentEle).each(function(childEle){
$.each(this.attributes, function(i, attrib) {
if(attrib.name === "type" && attrib.value === "Start"){
var end= childEle===parentEle.length-1 ? parentEle.nextSibling : parentEle[childEle+1];
// what goes here ?????
}
});
});
});
});
答:
-1赞
Mukund
11/16/2018
#1
不确定 xml 结构,但我认为我们可以使用像 xml2json 这样的模块有效地将 xml 解析为 json/object 结构,并使用 json 进行下一步操作。例如,如果我们考虑下面的 xml,
<root>
<xxx>
<txt>{{</txt>
</xxx>
<Err type="Start"/>
<xxx>
<txt>f</txt>
</xxx>
<xxx>
<txt>irst_name</txt>
</xxx>
<Err type="End"/>
<xxx>
<txt>}}</txt>
</xxx>
</root>
转换为 JSON 的代码将是,
var jsonObj = xml2json(xmlInput);
console.log(JSON.stringify(jsonObj, undefined, 4));
输出将是,
{
"root": {
"xxx": [
{
"txt": "{{"
},
{
"txt": "f"
},
{
"txt": "irst_name"
},
{
"txt": "}}"
}
],
"Err": [
{
"type": "Start"
},
{
"type": "End"
}
]
}
}
评论