javascript 使用 jQuery 将 xml 文档转换回字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22647651/
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 23:30:59  来源:igfitidea点击:

Convert xml document back to string with jQuery

javascriptjqueryxml

提问by Thijs Koerselman

I am trying to parse an xml formatted string, remove one of its elements, and write it back to a string. All with standard jQuery functions. It's the last step that I can't seem to figure out.

我试图解析一个 xml 格式的字符串,删除它的一个元素,然后将它写回一个字符串。全部使用标准的 jQuery 函数。这是我似乎无法弄清楚的最后一步。

var $xml = $(somexmlstring);
var element = $xml.find('name:contains("'+somevalue+'")');
element.remove();
var newxmlstring = $xml.dunno(); 

What function can I use to convert the $xml DOM back to a string?

我可以使用什么函数将 $xml DOM 转换回字符串?

采纳答案by RemyNL

To help you fix your code in the jsfiddle:

为了帮助您修复 jsfiddle 中的代码:

var data = '<value><url>foo</url><name>bar</name></value><value><url>foo</url><name>bar</name></value>'
var xml = $.parseXML('<root>' + data + '</root>');
var $xml = $(xml);
console.log('xml', $xml.find('root').html());

The fix is in the last line: `$xml.find('root').html()

修复在最后一行:`$xml。find('root').html()

回答by John S

You can use .html()if you wrap the jQuery object with a parent element first and then call .html()on the parent element.

.html()如果首先使用父元素包装 jQuery 对象,然后调用父元素,则可以使用.html()

var $xml = $(somexmlstring);
$xml.find('name:contains("' + somevalue + '")').remove();
var newxmlstring = $('<x></x>').append($xml).html(); 

This works even if the original XML string does not have a single root element. It does not work, however, if the original XML string contains an XML declaration (like <?xml version="1.0" encoding="UTF-8"?>).

即使原始 XML 字符串没有单个根元素,这也有效。但是,如果原始 XML 字符串包含 XML 声明(如<?xml version="1.0" encoding="UTF-8"?>),则它不起作用。

jsfiddle

提琴手



If the original XML string is a valid XML document, optionally containing an XML declaration at the beginning, you may want to create the jQuery object like this:

如果原始 XML 字符串是一个有效的 XML 文档,可以选择在开头包含一个 XML 声明,您可能希望像这样创建 jQuery 对象:

var $xml = $($.parseXML(somexmlstring).documentElement);
$xml.find('name:contains("' + somevalue + '")').remove();
var newxmlstring = $('<x></x>').append($xml).html(); 

jsfiddle

提琴手

回答by naren

You dont need jquery to this, use XMLSerializer

你不需要 jquery,使用 XMLSerializer

new XMLSerializer().serializeToString(xmlobj.documentElement);

回答by YMMD

As long as your XML document does not contain some extra fancy namespaces, then it's simple:

只要您的 XML 文档不包含一些额外的花哨的命名空间,那么它很简单:

var newxmlstring = $xml.html();