xml 在 Javascript 中将 XMLDocument 对象转换为字符串

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

Converting XMLDocument object to String in Javascript

javascriptxml

提问by paras2682

I want to convert XMLDocument object that I'm getting as a response from an ajax request, to a string. I tried using

我想将作为来自 ajax 请求的响应而获得的 XMLDocument 对象转换为字符串。我尝试使用

new XMLSerializer()).serializeToString(xmlObject)

and I get the following response:-

我得到以下回应:-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:errorList xmlns:ns2="http://www.example.com/api/delivery/V1"><error code="DOMAIN_VALIDATE" path="delivery.shipper"><message>empty</message></error><error code="DOMAIN_VALIDATE" path="delivery.shipperSite"><message>empty</message></error><error code="DOMAIN_VALIDATE" path="delivery.leg"><message>invalid</message></error></ns2:errorList>

Means the method converted the whole XMLDocument into string, including the very first tag

表示该方法将整个 XMLDocument 转换为字符串,包括第一个标签

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

I don't want this part of the response. Is there any method that does that. Note: I don't want to use the workarounds like "substr" etc.

我不想要这部分的回应。有没有什么方法可以做到这一点。注意:我不想使用“substr”等解决方法。

回答by Tim Down

You can do this by serializing just the root node:

您可以通过仅序列化根节点来做到这一点:

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

Demo: http://jsfiddle.net/timdown/LmWkL/

演示:http: //jsfiddle.net/timdown/LmWkL/