GVKun编程网logo

在C#中转义无效的XML字符(转义字符不正确)

20

本文的目的是介绍在C#中转义无效的XML字符的详细情况,特别关注转义字符不正确的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解在C#中转义无效的XML字符的机会,同时

本文的目的是介绍在C#中转义无效的XML字符的详细情况,特别关注转义字符不正确的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解在C#中转义无效的XML字符的机会,同时也不会遗漏关于c# – 有条件地转义特殊的xml字符、C#中的XML比较、Delphi:无效的XML通过MSXML验证、java – Track.getSimilar:在元素中找到了无效的XML字符(Unicode:0x3)…的知识。

本文目录一览:

在C#中转义无效的XML字符(转义字符不正确)

在C#中转义无效的XML字符(转义字符不正确)

我有一个包含无效XML字符的字符串。在解析字符串之前,如何转义(或删除)无效的XML字符?

答案1

小编典典

作为删除无效XML字符的方法,建议您使用XmlConvert.IsXmlChar方法。它是从.NET
Framework 4开始添加的,并且也在Silverlight中提供。这是小样本:

void Main() {    string content = "\v\f\0";    Console.WriteLine(IsValidXmlString(content)); // False    content = RemoveInvalidXmlChars(content);    Console.WriteLine(IsValidXmlString(content)); // True}static string RemoveInvalidXmlChars(string text) {    var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();    return new string(validXmlChars);}static bool IsValidXmlString(string text) {    try {        XmlConvert.VerifyXmlChars(text);        return true;    } catch {        return false;    }}

作为逃脱无效XML字符的方法,我建议您使用XmlConvert.EncodeName方法。这是小样本:

void Main() {    const string content = "\v\f\0";    Console.WriteLine(IsValidXmlString(content)); // False    string encoded = XmlConvert.EncodeName(content);    Console.WriteLine(IsValidXmlString(encoded)); // True    string decoded = XmlConvert.DecodeName(encoded);    Console.WriteLine(content == decoded); // True}static bool IsValidXmlString(string text) {    try {        XmlConvert.VerifyXmlChars(text);        return true;    } catch {        return false;    }}

更新:
应该提到的是,编码操作产生的字符串的长度大于或等于源字符串的长度。当您将编码后的字符串存储在具有长度限制的字符串列中的数据库中,并验证应用程序中的源字符串长度以适合数据列限制时,这可能很重要。

c# – 有条件地转义特殊的xml字符

c# – 有条件地转义特殊的xml字符

我已经环顾了很多但是却找不到只能转义特殊 XML字符的内置.Net方法:
<,>,&,’和“
如果它不是标签.

例如,采用以下文本:

Test& <b>bold</b> <i>italic</i> <<Tag index="0" />

我希望它转换为:

Test&amp; <b>bold</b> <i>italic</i> &lt;<Tag index="0" />

请注意,标签不会被转义.我基本上需要将此值设置为XmlElement的InnerXML,因此必须保留这些标记.

我已经研究了实现我自己的解析器并使用StringBuilder来尽可能地优化它,但它可能变得非常讨厌.

我也知道可以接受的标签可以简化事情(仅限:br,b,i,u,blink,flash,Tag).此外,这些标签可以是自闭标签

(e.g. <u />)

或容器标签

(e.g. <u>...</u>)

解决方法

注意:这可能是优化的.这只是我为你快速敲门的事情.另请注意,我没有对标签本身进行任何验证.它只是寻找包含在尖括号中的内容.如果在标签内找到尖括号,它也会失败(例如< soMetag label =“我把>这里”>).除此之外,我认为它应该做你想要的.
namespace ConsoleApplication1
{
    using System;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            // This is the test string.
            const string testString = "Test& <b>bold</b> <i>italic</i> <<Tag index=\"0\" />";

            // Do a regular expression search and replace. We're looking for a complete tag (which will be ignored) or
            // a character that needs escaping.
            string result = Regex.Replace(testString,@"(?'Tag'\<{1}[^\>\<]*[\>]{1})|(?'Ampy'\&[A-Za-z0-9]+;)|(?'Special'[\<\>\""\'\&])",(match) =>
                {
                    // If a special (escapable) character was found,replace it.
                    if (match.Groups["Special"].Success)
                    {
                        switch (match.Groups["Special"].Value)
                        {
                            case "<":
                                return "&lt;";
                            case ">":
                                return "&gt;";
                            case "\"":
                                return "&quot;";
                            case "\'":
                                return "&apos;";
                            case "&":
                                return "&amp;";
                            default:
                                return match.Groups["Special"].Value;
                        }
                    }

                    // Otherwise,just return what was found.
                    return match.Value;
                });

            // Show the result.
            Console.WriteLine("Test String: " + testString);
            Console.WriteLine("Result     : " + result);
            Console.ReadKey();
        }
    }
}

C#中的XML比较

C#中的XML比较

我正在尝试使用C#代码比较两个Xml文件。我想忽略Xml语法差异(即前缀名称)。为此,我使用了Microsoft的XML Diff和Patch C#API。它适用于某些Xml,但我找不到配置它以与以下两个Xml一起使用的方法:

XML A:

<root xmlns:ns="http://myNs">
  <ns:child>1</ns:child>
</root>

XML B:

<root>
  <child xmlns="http://myNs">1</child>
</root>

我的问题是:

  1. 我对这两个xml在语义上相等(或同构)是否正确?
  2. 可以配置Microsoft的XML Diff和Patch API来支持它吗?
  3. 还有其他C#实用程序吗?

Delphi:无效的XML通过MSXML验证

Delphi:无效的XML通过MSXML验证

我试图在MSDN上重新编写一个JScript示例,以便针对某些模式验证 XML.

作为第一个attmempt,我使用了示例中使用的sl-valid.xml,sl-notValid.xml和sl.xsd文件.

我的代码如下:

procedure BasicValidation(FileName: string);
var
  XML: IXMLDOMDocument2;
begin
  // Load XML and resolve externals
  XML := ComsDOMDocument.Create;
  XML.async := False;
  XML.validateOnParse := True;
  XML.resolveExternals := True;
  XML.setProperty('SelectionLanguage','XPath');
  XML.setProperty('SelectionNamespaces','xmlns:x=''urn:book''');
  XML.load(FileName);
  if XML.parseError.errorCode <> 0 then
    ShowMessage('Error parsing. Reason: ' + XML.parseError.reason)
  else
    ShowMessage('XML validation OK.');
end;

当我尝试sl-notValid.xml文件时,我仍然可以获得’XML验证’.有没有人见过这个?上述代码与JScript考试http://msdn.microsoft.com/en-us/library/ms764717%28VS.85%29.aspx之间的根本区别是什么?

解决方法

试试这个

procedure BasicValidation(FileName: string);
var
  XML: IXMLDOMDocument2;
begin
  XML := CodoMDocument40.Create;
  XML.async := False;
  XML.validateOnParse := True;
  XML.resolveExternals := True;
  XML.setProperty('SelectionLanguage','xmlns:x=''urn:book''');
  XML.load(FileName);
  if XML.parseError.errorCode <> 0 then
    ShowMessage('Error parsing. Reason: ' + XML.parseError.reason)
  else
    ShowMessage('XML validation OK.');
end;

说明,您必须显式调用支持XSD架构验证的版本的构造函数(MSXML> = 4).

再见.

java – Track.getSimilar:在元素中找到了无效的XML字符(Unicode:0x3)…

java – Track.getSimilar:在元素中找到了无效的XML字符(Unicode:0x3)…

我使用last.fm API: Api Last.fm

我有他们的艺术家的歌曲(曲目)列表,我想恢复每首歌曲,如他的歌曲. Track.getSimilar(Artist,track,key)的方法非常有效.但是当艺术家或曲目使用阿拉伯语时,我会遇到以下异常:

[Fatal error] :2583:13: An invalid XML character (Unicode: 0x3) was found in the element content of the document.
Exception in thread "main" de.umass.lastfm.CallException: org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x3) was found in the element content of the document.
at de.umass.lastfm.Caller.call(Caller.java:268)
at de.umass.lastfm.Caller.call(Caller.java:189)
at de.umass.lastfm.Track.getSimilar(Track.java:369)

我该如何解决这个问题呢?

先感谢您

解决方法

Unicode代码点0x3是控制字符.它不是任何脚本或语言系统中的正常字符,因此它的存在显然是一个错误,可能在数据库本身.这可能是编码转换失败,字符到字节转换或数据库写入损坏的结果.

XML不能包含控制字符 – 甚至不包含实体引用.因此,您的XML格式不正确,无法使用XML工具进行处理.相反,您需要使用字符串处理或类似方法删除该错误字符.

同时,您可以检查XML中非法的所有其他字符. XML不允许来自Unicode代理块[0xD800 – 0xDFFF]的任何字符,非字符0xFFFE和0xFFFF或低于0x20(=控制字符)的字符执行0x9 [tab],0xA [LF]和0xD [CR].这在这里正式陈述:http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char

今天的关于在C#中转义无效的XML字符转义字符不正确的分享已经结束,谢谢您的关注,如果想了解更多关于c# – 有条件地转义特殊的xml字符、C#中的XML比较、Delphi:无效的XML通过MSXML验证、java – Track.getSimilar:在元素中找到了无效的XML字符(Unicode:0x3)…的相关知识,请在本站进行查询。

本文标签: