我有一个问题,关于如何将文档类型定义包含到XML文件中,或者从WP7中加载到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 "è">
<!ENTITY eacute "é">
<!ENTITY euro "€">
]>
我需要将此DTD添加到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。 我已经尝试了许多基于this帖子使用XDocumentType的方法,但我无法弄清楚。 我怎么能这样做?
答案 0 :(得分:5)
您需要在阅读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
,可在不使用凭据的情况下解析网址。您可能需要考虑从本地源解析DTD。为此,您可以使用预先填充的XmlPreloadedResolver
。