我有一个字符串如下
<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>
我想获取附件中的值,也称为example_image_1_portrait_HD.jpg 如何使用jQuery做到这一点?
答案 0 :(得分:1)
通过将字符串传递到$
将字符串转换为jQuery集合,然后可以使用Attachments
获取.find('Attachments').text()
节点的文本:
const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';
console.log($(htmlStr).find('Attachments').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
但是请注意,完全不需要依赖像jQuery这样的大库来进行XML解析-您可以使用内置的DOMParser
来实现:
const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';
const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
console.log(doc.querySelector('Attachments').textContent);
答案 1 :(得分:1)
使用$ .parseXML()
var xml ="<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>";
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "Attachments" );
console.log($title.text());