1

I have the following XML, it's coming as string from a request. How can I get the capital value (Washington, DC Paris)?

<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>

2 Answers 2

4

Use a DomParser :

var xml = `<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>`

var parser = new DOMParser();
var doc = parser.parseFromString(xml, "application/xml");
doc.querySelectorAll('Capital').forEach(
  (cap) => console.log(cap.textContent));

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

Comments

1

Adding the answer with jquery. With jquery it can be easily done as,

var text = `<Country>
    <USA>
    <Capital>"Washington, D.C"</Capital>
    </USA>
    <France>
    <Capital>"Paris"</Capital>
    </France>
</Country>`;
$(text).find("Capital").each(function(){
console.log($(this).text());
    }); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

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.