【问题标题】:Does LINQ to XML ignore includes from a DTD?LINQ to XML 是否忽略 DTD 中的包含?
【发布时间】:2011-07-20 11:05:05
【问题描述】:

我正在使用 MathML DTD 使用 System.Xml.Linq. 解析 MathML 虽然普通的 MathML 内容可以很好地识别,但 DTD 中包含的 MMLEXTRA 会被忽略并且出现错误。这是我正在使用的代码:

  if (!string.IsNullOrWhiteSpace(mathML))
  {
    try
    {
      const string preamble =
          "<!DOCTYPE mml:math PUBLIC \"-//W3C//DTD MathML 2.0//EN\"\n" +
           "\"http://www.w3.org/Math/DTD/mathml2/mathml2.dtd\" [\n" +
           "<!ENTITY % MATHML.prefixed \"INCLUDE\">\n" +
           "<!ENTITY % MATHML.prefix \"mml\"> \n" +
         "]>";
      var parsed = Parser.Parse(preamble + Environment.NewLine + mathML);
      textEditor.Text = printed;
      lblStatus.Caption = "MathML successfully translated.";
    } 
    catch (Exception e)
    {
      lblStatus.Caption = "Cannot translate text. " + e.Message;
    }
  }

解析器只执行XDocument.Load()。任何帮助表示赞赏!

【问题讨论】:

  • @Kirk Parser 只是一个基本上做XDocument.Load 的组件。假设此调用将直接解析所有 MathML 引用,但事实并非如此。

标签: c# xml linq-to-xml dtd mathml


【解决方案1】:

来自here

DTD 中的实体本质上是不安全的。这是可能的 包含导致解析器使用的 DTD 的恶意 XML 文档 所有内存和 CPU 时间,导致拒绝服务攻击。 因此,在 LINQ to XML 中,DTD 处理默认是关闭的。 您不应接受来自不受信任来源的 DTD。

但是,要启用它,您应该使用XDocumentType class

几个可能的解决方案:

XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = false;

XmlReader reader = XmlReader.Create(Server.MapPath("filename"), settings);

XDocument doc = XDocument.Load(reader);

或许:

 XDocument xDocument = new XDocument(new XDocumentType("Books",null,"Books.dtd", null),new XElement("Book"));

所有信息都来自同一个source

【讨论】:

  • 太棒了!这完全适合我。呸!花费了 50 个代表点,但我的产品是安全的 :) 谢谢!
  • 引用的答案与当前的 MS 文档相矛盾,即“当文档包含在 DTD 中定义的实体引用时,引用会在创建 XML 树时展开”:docs.microsoft.com/en-us/dotnet/api/… 也许有在这 9 年的某个时候,这是一个设计变更决定。
猜你喜欢
  • 1970-01-01
  • 2012-07-13
  • 1970-01-01
  • 2023-03-22
  • 2023-03-06
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多