使用 jQuery 将 xml 转换为字符串

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

Convert xml to string with jQuery

jqueryxmlxml-serializationtostring

提问by Yarin

I'm loading an xml file with jQuery ajax loader, and need to convert it to a string so that I can save it out again using PHP post variables. What is the best way to do this?

我正在使用 jQuery ajax 加载器加载一个 xml 文件,并且需要将其转换为字符串,以便我可以使用 PHP post 变量再次将其保存。做这个的最好方式是什么?

<script type='text/javascript'>

jQuery.ajax({
    type: "GET",
    url: "data.xml",
    dataType: "xml",
    success: parseXML
    });


function parseXML(xml) {

    var xml_string = jQuery(xml).text();  // (This doesn't work- returns tagless, unformatted text) 
    alert(xml_string);

}

</script>

回答by Yarin

Here it is:

这里是:

<script type='text/javascript'>

function xmlToString(xmlData) { 

    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData);
    }
    return xmlString;
}   

</script>

Taken from here

取自这里

回答by Gojko Adzic

this works around the .innerHtml problem.

这可以解决 .innerHtml 问题。

$('<div>').append(xmlObj).html()

回答by Ben

This worked for me (credit: http://www.ibm.com/developerworks/xml/tutorials/x-processxmljquerytut/section3.html):

这对我有用(信用:http: //www.ibm.com/developerworks/xml/tutorials/x-processxmljquerytut/section3.html):

 function getXmlAsString(xmlDom){
      return (typeof XMLSerializer!=="undefined") ? 
           (new window.XMLSerializer()).serializeToString(xmlDom) : 
           xmlDom.xml;
 }          

Here's an example that retrieves information about a column from a SharePoint list:

下面是从 SharePoint 列表中检索有关列的信息的示例:

var soapEnv =
    "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
        <soapenv:Body> \
             <GetList xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
                <rowLimit>0</rowLimit> \
                <listName>Announcements</listName> \
            </GetList> \
        </soapenv:Body> \
    </soapenv:Envelope>";


jQuery.support.cors = true; 
$.ajax({
    url: "http://sharepoint/_vti_bin/lists.asmx",
    type: "POST",
    dataType: "xml",
    data: soapEnv,
    contentType: "text/xml; charset=\"utf-8\"",
    complete: function(xData){
        var xmlDoc = $.parseXML(xData.responseText), $xml = $(xmlDoc)           
        $Fields = $xml.find("Field");
        $field = $Fields.filter("Field[Name='Title']")[0];

        //Show the xml
        alert(getXmlAsString( xmlDoc ));
        alert(getXmlAsString( $field ));
    }
});

回答by Michael T

Spent much time for this problem. With IE 9 above functions should work in another way. Because in IE9 xmlData[0].xmldoesn't work (IE still likes jokes). And we must use XMLSerializerwith IE v9 and higher (?!)

花了很多时间解决这个问题。使用 IE 9 以上的功能应该以另一种方式工作。因为在 IE9xmlData[0].xml中不起作用(IE 仍然喜欢开玩笑)。我们必须使用XMLSerializerIE v9 及更高版本 (?!)

function xmlToString(xmlData) { // this functions waits jQuery XML 

    var xmlString = undefined;

    if (window.ActiveXObject){
        xmlString = xmlData[0].xml;
    }

    if (xmlString === undefined)
    {
        var oSerializer = new XMLSerializer();
        xmlString = oSerializer.serializeToString(xmlData[0]);
    }

    return xmlString;
}

And example of using it with jQuery 1.8.2 (1.6.4 works too).

以及将它与 jQuery 1.8.2 一起使用的示例(1.6.4 也适用)。

   $.ajax(
        {
            type: type,
            url: url,
            data: values,
            dataType: 'html', //get response in plain text
            success: function(response) {    

                //transform it to jQuery XML DOM
                var xmlDoc = jQuery.parseXML(response);
                var xml = $(xmlDoc);

                //do some search and so on
                var divtag = xml.find('div[id="content"]');
                var divtxt = xmlToString(divtag);

                //consume it
                alert(divtxt);
                $('#main-content').html(divtxt);

            }
        });

回答by Andy Widdess

Had the same problem - xmlString was returning an empty string. Adding [0] to jQuery selector helped to address XML-type object:

有同样的问题 - xmlString 返回一个空字符串。将 [0] 添加到 jQuery 选择器有助于解决 XML 类型的对象:

Your Javascript:

你的Javascript:

<script type='text/javascript'>
function xmlToString(xmlData) 
{
    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData[0]);
    }
    return xmlString;
}   
</script>

jQuery:

jQuery:

<script>
$(function(){ 
  xmlData = "<tag>just a sample here</tag>"; 
  xmlData= $(xmlData); 
  if (window.ActiveXObject){ 
    var xmlString = xmlData.xml; 
  } else {
    var oSerializer = new XMLSerializer(); 
    var xmlString = oSerializer.serializeToString(xmlData[0]);
  } 
  console.log(xmlString); 
})
</script>

回答by Sujan Shrestha

You can use following function:

您可以使用以下功能:

function getXmlString($xmlObj)
{   
    var xmlString="";
    $xmlObj.children().each(function(){
        xmlString+="<"+this.nodeName+">";
        if($(this).children().length>0){
            xmlString+=getXmlString($(this));
        }
        else
            xmlString+=$(this).text();
        xmlString+="</"+this.nodeName+">";
    });
    return xmlString;
}

Pass jquery xml object to this function

将 jquery xml 对象传递给这个函数

回答by Bo Hu

function serializeXML(xmldom) {
  if (typeof XMLSerializer != "undefined") {
    return (new XMLSerializer()).serializeToString(xmldom);
  } else if (typeof xmldom.xml != "undefined") {
    return xmldom.xml;
  } else {
    throw new Error("Could not serialize XML DOM.");
  }
}

// test
var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
  xmlDoc = $.parseXML(xml),
  xmlStr = serializeXML(xmlDoc);
console.log("xmlStr: " + xmlStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by Mr AH

An old post I know but thought I would suggest this:

我知道的一个旧帖子,但我想我会建议这个:

xml[0].outerHTML

回答by Ajeet Kumar Singh

In my case

就我而言

if(window.ActiveXObject){
    xmlString = xmlData.xml;
}

Is not working. This is issue with IE10.

不管用。这是IE10 的问题。

So I am able to fix this issue as follows:

所以我可以按如下方式解决这个问题:

if(window.ActiveXObject){
    xmlString = xmlData.attr('xml');
}

And working fine with any browser.

并且可以在任何浏览器上正常工作。

回答by Purushotham Racharla

Just access xml as attribute value of jQuery object. as simple as that.

只需访问 xml 作为 jQuery 对象的属性值。就如此容易。