0

I have a string as below

<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>

I want to get the values inside Attachments, aka example_image_1_portrait_HD.jpg How to do this using jQuery?

2 Answers 2

1

Use $.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());
Sign up to request clarification or add additional context in comments.

Comments

1

Turn the string into a jQuery collection by passing it to $, and then you can get the text of the Attachments node with .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>

But note that there's no need at all to depend on a big library like jQuery just for XML parsing - you can achieve this using the built-in DOMParser instead:

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

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.