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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:49:50  来源:igfitidea点击:

Get node value in XML using jQuery

javascriptjqueryxml

提问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 AssetImageIdvalue. 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

演示:小提琴