我有一个返回XElement对象的C# API。这个XElement对象是通过以下代码构建的 -
通过观察,我知道当尝试将无效的 XML 字符传递给上面的 XElement 构造函数时,会引发 System.Argument 异常。
所以事实证明,当传递包含无效 XML 字符的字符串时,XElement 不会抛出错误。如果您尝试通过 Console.WriteLine(fe) 打印 XElement,则会从 XMLWriter 收到异常。
对我来说,似乎XElement本身并不进行任何验证。在.NET中,当它被打印/序列化时,内部会调用XML writer,这时会抛出异常。
我的问题是,XElement是否保证如果传递了无效的XML字符就会抛出异常?
换句话说,我需要检查我传递的字符串是否存在无效的XML字符吗?使用类似XmlConvert.IsXmlChar(string)的东西?
我看了下面的链接,但没有找到令人满意的答案-
string invalidXML = "a \v\f\0";
XElement fe = new XElement("Data", invalidXML);
Console.WriteLine(fe);
通过观察,我知道当尝试将无效的 XML 字符传递给上面的 XElement 构造函数时,会引发 System.Argument 异常。
所以事实证明,当传递包含无效 XML 字符的字符串时,XElement 不会抛出错误。如果您尝试通过 Console.WriteLine(fe) 打印 XElement,则会从 XMLWriter 收到异常。
System.ArgumentException: '', hexadecimal value 0x0B, is an invalid character.
at System.Xml.XmlEncodedRawTextWriter.InvalidXmlChar(Int32 ch, Char* pDst, Boolean entitize)
at System.Xml.XmlEncodedRawTextWriter.WriteElementTextBlock(Char* pSrc, Char* pSrcEnd)
at System.Xml.XmlEncodedRawTextWriter.WriteString(String text)
at System.Xml.XmlEncodedRawTextWriterIndent.WriteString(String text)
at System.Xml.XmlWellFormedWriter.WriteString(String text)
at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
at System.Xml.Linq.XNode.ToString()
at System.IO.TextWriter.WriteLine(Object value)
at System.IO.TextWriter.SyncTextWriter.WriteLine(Object value)
at System.Console.WriteLine(Object value)
at TestLoggingForUNIT.Program.Main(String[] args) in C:\Users\shivanshu\source\repos\TestLoggingForUNIT\TestLoggingForUNIT\Program.cs:line 29
对我来说,似乎XElement本身并不进行任何验证。在.NET中,当它被打印/序列化时,内部会调用XML writer,这时会抛出异常。
我的问题是,XElement是否保证如果传递了无效的XML字符就会抛出异常?
换句话说,我需要检查我传递的字符串是否存在无效的XML字符吗?使用类似XmlConvert.IsXmlChar(string)的东西?
我看了下面的链接,但没有找到令人满意的答案-