2013-03-06 8 views
1

.stringify 메서드를 사용하여 JSON 문자열로 쉽게 변환 할 수있는 다차원 Javascript 객체가 있습니다. 유사한 기능을 XML, 마크 업 형식으로 작성하려고합니다. 캐치는 모든 치수를 처리 할 수 ​​있기를 바랍니다.Javascript에서 XML로 여러 수준의 문자열

의이 그래서 같은 값으로 다차원 개체 다음 내가 있다고 가정 해 봅시다 :

object['annualrevenues']['option0']['ID'] = 1; 
object['annualrevenues']['option0']['text'] = '$50mil'; 
object['annualrevenues']['option1']['ID'] = 2; 
object['annualrevenues']['option1']['text'] = '$100mil'; 
object['annualrevenues']['option2']['ID'] = 3; 
object['annualrevenues']['option2']['text'] = '$200mil'; 

내가 너무 좋아하는 캐릭터 라인을 구축하려는 : 한 번에 대한 응답으로 반환

var xmlText = <xml><annualrevenues><option0><ID>1</ID><text>$50</text></option0></annualrevenues></xml> 

contentType 'XMLDOC'은 다음과 같습니다.

<xml> 
    <annualrevenues> 
    <option0> 
     <ID>1</ID> 
     <text>$50</text> 
    </option0> 
    </annualrevenues> 
</xml> 

그래서 다음과 같은 기능이 있습니다 :

var xmlText = '<xml>'; 
    xmlText += formatXMLSubObjects(objText,xmlText); 

function formatXMLSubObjects(objText,xmlText){ 
    for (prop in objText) { 
    if (typeof objText[prop] == 'object') { 
     xmlText += '<'+prop+'>'; 
     for (subProp in objText[prop]) { 
      if (typeof objText[prop][subProp] == 'object') { 
       // Run the function again as recursion 
       xmlText += formatXMLSubObjects(objText[prop][subProp],xmlText); 
      } 
      else { 
       xmlText += '<' + subProp + '>' + objText[prop][subProp] + '</' + subProp + '>'; 
      } 
     } 
     xmlText += '</'+prop+'>'; 
    } 
    else { 
     xmlText += '<'+prop+'>'+objText[prop]+'</'+prop+'>'; 
    } 
    } 
return xmlText; 
} 

문제는 formatXMLSubObjects 함수가 두 번째 호출에서 반환 될 때 첫 번째 호출의 원래 개체를 덮어 쓰고 이제 정의되지 않은 것입니다.

누구든지 도움을 줄 수 있습니까?

+0

는 함수 외부 변수에 객체를 저장할? – Christophe

답변

2

함수 내에서 xmlText의 정의를 이동하고 초기 페이로드 및 for 루프의 외부 변수를 포함하기 위해 다른 변수를 외부로 사용합니다. 그렇지 않으면 전역 변수로 덮어 쓰여지고 xmlText를 전달하지 않습니다 호출에 연결하지만 결과를 매번 이전 연결과 연결하십시오.

function formatXMLSubObjects(objText) { 
    var xmlText = ""; // this will contain only this chunk of the object 

    for (var prop in objText) { 
     xmlText += '<'+prop+'>'; // place the tag anyway 
     if (typeof objText[prop] == 'object') { 
      xmlText += formatXMLSubObjects(objText[prop]); // if it's an object recurse 
     } else { 
      xmlText += objText[prop]; // ... otherwise just add the value (this will work only for simple values 
     } 
    xmlText += '</' + prop + '>'; 
    } 
    return xmlText; 
} 

var xml = '<xml>'; 
xml += formatXMLSubObjects(obj); 
xml += '</xml>'; 

이 바이올린에서보세요 : http://jsfiddle.net/vZjAP/

+0

신난다, 고마워! – MBguitarburst