在使用XMLSerializer()序列化之前从XML中删除无效字符 [英] Removing invalid characters from XML before serializing it with XMLSerializer()

查看:155
本文介绍了在使用XMLSerializer()序列化之前从XML中删除无效字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户输入存储在客户端(javascript)的XML文档中,并将其传输到服务器以实现持久性。

I'm trying to store user-input in an XML document on the client-side (javascript), and transmit that to the server for persistence.

例如,一个用户粘贴在包含STX字符(0x2)的文本中。 XMLSerializer没有转义STX字符,因此没有序列化为格式良好的XML。或者.attr()调用可能已经转义了STX字符,但在任何一种情况下,都产生了无效的XML。

One user, for example, pasted in text that included an STX character (0x2). The XMLSerializer did not escape the STX character, and therefore, did not serialize to well-formed XML. Or perhaps the .attr() call should have escaped the STX character, but in either case, invalid XML was produced.

我找到了浏览器的输出XMLSerializer()并不总是格式良好,(甚至不满足浏览器自己的DOMParser()

I'm finding the output of in-browser XMLSerializer() isn't always well-formed, (and doesn't even satisfy the browser's own DOMParser()

此示例显示STX字符未正确编码通过XMLSerializer():

This example shows that the STX character is not properly encoded by XMLSerializer():

> doc = $.parseXML('<?xml version="1.0" encoding="utf-8" ?>\n<elem></elem>');
    #document
> $(doc).find("elem").attr("someattr", String.fromCharCode(0x2));
    [ <elem someattr=​"">​</elem>​ ]
> serializedDoc = new XMLSerializer().serializeToString(doc);
    "<?xml version="1.0" encoding="utf-8"?><elem someattr=""/></elem>"
> $.parseXML(serializedDoc);
    Error: Invalid XML: <?xml version="1.0" encoding="utf-8"?><elem someattr=""/></elem>

我应该如何在浏览器中构建XML文档(使用由任意用户输入确定的参数),以便它始终是格式良好的(一切都正确转义)?我不需要支持IE8或IE7。

How should I construct an XML document in-browser (with params determined by arbitrary user-input) such that it will always be well-formed (everything properly escaped)? I don't need to support IE8 or IE7.

(是的,我确实在服务器端验证XML,但是如果浏览器向服务器提交了一份文件,没有格式良好,服务器可以做的最好是拒绝它,这对穷人用户没有帮助)

(And yes, I do validate the XML on the server side, but if the browser hands the server a document that is not well-formed, the best the server can do is reject it, which isn't that helpful to the poor user)

推荐答案

这是一个函数 sanitizeStringForXML(),它可以用于在赋值之前清理字符串,也可以用于衍生函数 removeInvalidCharacters(xmlNode),它可以传递给DOM树,并且自动清理属性和textNodes,以便它们可以安全存储。

Here's a function sanitizeStringForXML() which can either be used to cleanse strings before assignment, or a derivative function removeInvalidCharacters(xmlNode) which can be passed a DOM tree and will automatically sanitize attributes and textNodes so they are safe to store.

var stringWithSTX = "Bad" + String.fromCharCode(2) + "News";
var xmlNode = $("<myelem/>").attr("badattr", stringWithSTX);

var serializer = new XMLSerializer();
var invalidXML = serializer.serializeToString(xmlNode);

// Now cleanse it:
removeInvalidCharacters(xmlNode);
var validXML = serializer.serializeToString(xmlNode);

我基于此维基百科文章的非限制字符部分,但补充平面需要5个十六进制数字的unicode字符,而Javascript正则表达式不包含此语法,因此对于现在,我只是把它们剥掉了(你没有错过太多......):

I based this on a list of characters from the non-restricted characters section of this wikipedia article, but the supplementary planes require 5-hex-digit unicode characters, and the Javascript regex does not include a syntax for this, so for now, I'm just stripping them out (you aren't missing too much...):

// WARNING: too painful to include supplementary planes, these characters (0x10000 and higher) 
// will be stripped by this function. See what you are missing (heiroglyphics, emoji, etc) at:
// http://en.wikipedia.org/wiki/Plane_(Unicode)#Supplementary_Multilingual_Plane
var NOT_SAFE_IN_XML_1_0 = /[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm;
function sanitizeStringForXML(theString) {
    "use strict";
    return theString.replace(NOT_SAFE_IN_XML_1_0, '');
}

function removeInvalidCharacters(node) {
    "use strict";

    if (node.attributes) {
        for (var i = 0; i < node.attributes.length; i++) {
            var attribute = node.attributes[i];
            if (attribute.nodeValue) {
                attribute.nodeValue = sanitizeStringForXML(attribute.nodeValue);
            }
        }
    }
    if (node.childNodes) {
        for (var i = 0; i < node.childNodes.length; i++) {
            var childNode = node.childNodes[i];
            if (childNode.nodeType == 1 /* ELEMENT_NODE */) {
                removeInvalidCharacters(childNode);
            } else if (childNode.nodeType == 3 /* TEXT_NODE */) {
                if (childNode.nodeValue) {
                    childNode.nodeValue = sanitizeStringForXML(childNode.nodeValue);
                }
            }
        }
    }
}

请注意,这只会从属性和textNodes的nodeValues中删除无效字符。它不会检查标签名称或属性名称,注释等等。

Note that this only removes invalid characters from nodeValues of attributes and textNodes. It does not check tag names or attribute names, comments, etc etc.

这篇关于在使用XMLSerializer()序列化之前从XML中删除无效字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆