获取XML字段值javascript

时间:2019-02-24 13:32:17

标签: javascript xml

我有以下XML,它是来自请求的字符串。如何获得资本价值(华盛顿特区巴黎巴黎)?

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

2 个答案:

答案 0 :(得分:3)

使用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));

答案 1 :(得分:1)

使用jquery添加答案。使用jquery可以很容易地完成

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>