如何加载用于XDocument的内联DTD

本文关键字:XDocument DTD 用于 何加载 加载 | 更新日期: 2023-09-27 18:01:22

我有一个问题,关于如何在WP7中将文档类型定义包含到XML文件中,或者从正在加载到XDocument中的XML文件中包含文档类型定义。我有一个类似这样的DTD文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE root [
 <!ELEMENT root (Person*)>
 <!ELEMENT Person (Name*, Description*)>
 <!ELEMENT Name (#PCDATA)>
 <!ELEMENT Description (#PCDATA)>
 <!ENTITY egrave "&#232;">
 <!ENTITY eacute "&#233;">
 <!ENTITY euro  "&#8364;">
]>

我需要将这个DTD添加到捕获特殊字符(如&eacute;)的XML中。我正在使用以下方法从web获得XML在Linq中使用:

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
  string documentUrl = "http://www.example.com";
  WebClient client = new WebClient();
  client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
  client.OpenReadAsync(new Uri(documentUrl, UriKind.Absolute));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  Stream str = e.Result;
  XDocument data = XDocument.Load(str);
  // Saving the XML to the file system for later use
  IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication();
  IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("my.xml", FileMode.OpenOrCreate, isoFile);
  StreamWriter sw = new StreamWriter(isoStream);
  XmlWriter xw = XmlWriter.Create(isoStream);
  data.Save(xw);
  // Creating a list to populate a listbox
  List<MyObject> list1 = new List<MyObject>();
  items = (from query in data.Descendants("Person")
    select new MyObject()
    {
    // Doing stuff here...
    }).ToList();
  listBox1.ItemsSource = items;
}

如果DTD内联,即在实际的XML本身中,XDocument似乎不会传递XML。基于这篇文章,我尝试了许多使用XDocumentType的方法,但我还是无法找到它。我该怎么做呢?

如何加载用于XDocument的内联DTD

在读取XML文档时需要启用DTD处理。要做到这一点,请使用具有适当设置的XmlReader:

var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse };
XmlReader reader = XmlReader.Create(str, settings);
XDocument data = XDocument.Load(reader);

如果您想要外部DTD,您需要在设置中指定XmlResolver:

var settings = new XmlReaderSettings
{
    DtdProcessing = DtdProcessing.Parse,
    XmlResolver = /* some resolver here */,
};

默认的XmlResolver是一个XmlUrlResolver,它在不使用凭证的情况下解析url。您可能需要考虑从本地源解析DTD。为此,您可以使用预填充的XmlPreloadedResolver