1

Im trying to bind XML data to a variable in AngularJS.

The data returned from my service is in XML

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
&lt;Response&gt;&#xD;
  &lt;Firstname&gt;Johanna&lt;/Firstname&gt;&#xD;
&lt;/Response&gt;</string>

I then use x2js to parse the xml and get this returned:

var jsonResponse = x2js.xml_str2json(response);

enter image description here

Finally I want to bind Firstname to $scope.firstname

This is where I need help. I dont know what to do to bind the value. What ive tried:

$scope.firstname = jsonResponse.Response.Firstname;
> TypeError: Cannot read property 'Firstname' of undefined

$scope.firstname = jsonResponse.Object.Object.toString.__text.Response.Firstname
> TypeError: Cannot read property 'Object' of undefined

Ive tried a bunch of different combinations to try get to Firstname but none are working. I either get the above error or an undefined message.

What am I doing wrong? Please help.

1 Answer 1

1

Convert your xml string to which contains special characters needs to decode in HTML and than convert it to JSON please find below snippet for more information.

I have added a function for DecodeHTML similarly you can choose if you have any other option to Decode it.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
var x2js = new X2JS();
var xmlstring = '<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;Response&gt;&#xD;&lt;Firstname&gt;Johanna&lt;/Firstname&gt;&#xD;&lt;/Response&gt;</string>';

var formattedXML = decodeHtml(xmlstring);
var xmlTOjson = x2js.xml_str2json(formattedXML);

var FirstName = xmlTOjson.string.Response.Firstname;

alert(FirstName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome!! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.