javascript 使用 jQuery 获取 XML 中的节点值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20136280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get node value in XML using jQuery
提问by fulvio
I'm trying to parse the following XML:
我正在尝试解析以下 XML:
<AssetImageModel xmlns="http://schemas.datacontract.org/2004/07/ErgonFileService.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AssetId>00000000-0000-0000-0000-000000000000</AssetId>
<AssetImageId>b74af53a-91e6-83f5-26f9-e1719ad5fd05</AssetImageId>
<ImagePath i:nil="true"/>
<IsDeleted>false</IsDeleted>
<Modified>false</Modified>
<Version>0</Version>
</AssetImageModel>
In order to retrieve for example the AssetImageId
value. What would be the easiest way to achieve this using either JS or jQuery?
例如为了检索AssetImageId
值。使用 JS 或 jQuery 实现这一目标的最简单方法是什么?
回答by Arun P Johny
If you are having a xml text then use $.parseXML() to parse it to a xml object then use find() to locate the element.
如果您有一个 xml 文本,则使用 $.parseXML() 将其解析为 xml 对象,然后使用 find() 来定位该元素。
var text = '<AssetImageModel xmlns="http://schemas.datacontract.org/2004/07/ErgonFileService.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><AssetId>00000000-0000-0000-0000-000000000000</AssetId><AssetImageId>b74af53a-91e6-83f5-26f9-e1719ad5fd05</AssetImageId><ImagePath i:nil="true"/><IsDeleted>false</IsDeleted><Modified>false</Modified><Version>0</Version></AssetImageModel>'
var xml = $.parseXML(text);
console.log($(xml).find('AssetImageId').text())
Demo: Fiddle
演示:小提琴
If you are using ajax then set the dataType: 'xml'
so that you can get the parsed object as the data in your success handler
如果您使用的是 ajax,则设置dataType: 'xml'
以便您可以将解析的对象作为成功处理程序中的数据
Demo: Fiddle
演示:小提琴