3

我有一个返回 XElement 对象的 C# API。这个 XElement 对象是通过如下代码构造的 -

string invalidXML = "a \v\f\0";    
XElement fe = new XElement("Data", invalidXML);
Console.WriteLine(fe);

通过观察,我知道当尝试将无效的 XML 字符传递给上面的 XElement 构造函数时,会引发System.Argument异常。

事实证明,当传递带有 InvalidXML 字符的字符串时,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 编写器,这就是引发异常的时候。

我的问题是,XElement 总是保证如果传递了无效的 XML 字符就会引发异常。

换句话说,我是否需要检查我传递的字符串是否存在无效的 XML 字符?使用类似 XmlConvert.IsXmlChar(string) 的东西?

我查看了下面的链接,但找不到对我的问题满意的答案-

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/valid-content-of-xelement-and-xdocument-objects3

4

0 回答 0