XDocument.Load()在DTD头中引入了空的InternalSubset

时间:2014-03-26 15:19:08

标签: c# .net xml linq-to-xml

鉴于输入:

<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.020/cXML.dtd">
<cXML />

我的代码返回了:

<!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.020/cXML.dtd"[]>
<cXML />

引入的空InternalSubset([])给我带来了麻烦,所以我试图找出问题的根源。事实证明,XDocument.Load()是执行以下操作的罪魁祸首:

case XmlNodeType.DocumentType: 
  c.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value, r.DtdInfo));

r.Value是一个空字符串而不是null,因此XDocument.DocumentType.InternalSubset是一个空字符串而不是null

以下是示例代码:

XDocument doc = new XDocument(
                new XDeclaration("1.0", Encoding.UTF8.WebName.ToUpper(), string.Empty),
                new XDocumentType("cXML", null, "http://xml.cxml.org/schemas/cXML/1.2.020/cXML.dtd", null),
                new XElement("cXML"));

TextWriter writer = new StringWriter();
doc.Save(writer);
doc.Dump();
doc = XDocument.Load(new StringReader(writer.ToString()));
doc.Dump();

1 个答案:

答案 0 :(得分:0)

这应该在Load()之后调用时解决问题:

if (doc.DocumentType != null && doc.DocumentType.InternalSubset == string.Empty)
{
   doc.DocumentType.InternalSubset = null;
}