jQuery XML 구문 분석/트래 버스
-
06-07-2019 - |
문제
나는 다음 xml-
<rows>
<row id="5">
<cell>Item1</cell>
<attrs>
<attr>
<id>1</id>
<type>CheckBox</type>
<values>
<value>
<id>10</id>
</value>
<value>
<id>11</id>
</value>
</values>
</attr>
<attr>
<id>2</id>
<type>CheckBox</type>
<values>
<value>
<id>20</id>
</value>
<value>
<id>21</id>
</value>
</values>
</attr>
</attrs>
</row>
</rows>
내가하고 싶은 것은 특정 행의 각 행을 루프하는 것입니다.
나는 모든 attds를 얻기 위해 이것을 시도했지만 값 ID도 얻었습니다.
function fillForm(id){
var theRow = $(theXmlDoc).find('row[id='+id+']').get()
$(theRow).find("attr").each(function(i)
{
alert($(this).find("id").text());
});
}
또한 메인 목표는 각 attr을 루프 한 후 attr의 ID를 가지고있는 동안 각 값을 루프하는 것입니다.
추신 : 다른 도서관에서 더 쉽고 간단한 방법을 생각한다면 제안을 할 수 있습니다.
미리 감사드립니다.
해결책
나는 당신이 무엇을 반복 시키려고 노력하는지 명확하지 않습니다. 당신의 질문에있는 태그 중 하나가 잡힌 것이라고 생각합니다. "내가하고 싶은 것은 특정 행의 각 행을 루프하는 것입니다." 그리고 나는 당신이 거기에 태그가 있다고 생각합니다.
어쨌든 다음은 jQuery를 사용하여 구문 분석 된 XML 문서에서 데이터를 추출하는 몇 가지 예입니다. 의견은 무엇을 경고 할 것인지를 보여줍니다.
문제의 일부는 당신이 속성에 대한 자녀보다는 형제 자매로 ID 값을 가지고 있다는 것입니다. 더 일관된 구조는 다음과 같습니다.
<rows>
<row id="5">
<cell>Item1</cell>
<attrs>
<attr id="1">
<type>CheckBox</type>
<values>
<value>
<id>10</id>
</value>
<value>
<id>11</id>
</value>
</values>
</attr>
<attr id="2">
<type>CheckBox</type>
<values>
<value>
<id>20</id>
</value>
<value>
<id>21</id>
</value>
</values>
</attr>
</attrs>
</row>
</rows>
그러나 XML을 통제 할 수 없다면 해당 제안을 무시하십시오. :-)
좋아, 여기에 다양한 데이터를 얻기위한 트래버스 샘플이 있습니다.
먼저 "Item1"을 얻으십시오.
<script type="text/javascript">
// Item1
$.get('sample.xml', null, function (data, textStatus) {
alert( $(data).find('rows row[id=5] cell').text());
}, 'xml');
</script>
이제 우리는 1과 2를 얻을 것입니다.
<script type="text/javascript">
// 1
// 2
$.get('sample.xml', null, function (data, textStatus) {
$(data).find('rows row[id=5] attrs attr > id').each( function(){
alert($(this).text()); // 1, 2
});
}, 'xml');
</script>
그리고 마지막으로, 메인 어트로 ID를 꺼내 값으로 묶어 봅시다.
<script type="text/javascript">
// rows row[id=5] attrs attr > id 1 has inner ids of 10,11
// rows row[id=5] attrs attr > id 2 has inner ids of 20,21
$.get('sample.xml', null, function (data, textStatus) {
var out = ''
$(data).find('rows row[id=5] attrs attr > id').each( function(){
out += 'rows row[id=5] attrs attr > id ' + $(this).text();
var innerIds = [];
$(this).siblings('values').find('value id').each(function(){
innerIds.push($(this).text())
});
out += ' has inner Ids of ' + innerIds.join(',') + '\n';
});
alert(out);
}, 'xml');
</script>
다른 팁
이것은 당신을 위해 효과가 있습니다
function fillForm(id){
var row = $(theXmlDoc).find('row#+'+ id);
var ids = row.find( "attr > id");
ids.each(function(i)
{
alert($(this).text());
});
}
추신. 당신이 사용할 수있는 xpath 어느 하나:
var ids = document.evaluate( '//rows/row[@id='+id + ']/attr/id/text( )', theXmlDoc, null, XPathResult.ANY_TYPE, null );
제휴하지 않습니다 StackOverflow