由于分辨率错误,XDocument.Parse失败,如何禁用分辨率

时间:2010-05-24 18:23:31

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

我正在尝试使用XDocument.Parse(string)解析http://feeds.feedburner.com/riabiz的内容(因为它会缓存在数据库中。)

但是,当它尝试解析该XML中的某些URI时,它仍然无法使用下面的堆栈跟踪。

我不关心验证或任何XML废话,我只想解析结构。如何在没有此URI解析的情况下使用XDocument?

System.ArgumentException: The specified path is not of a legal form (empty).
  at System.IO.Path.InsecureGetFullPath (System.String path) [0x00000] in
:0 
  at System.IO.Path.GetFullPath (System.String path) [0x00000] in :0 
  at System.Xml.XmlResolver.ResolveUri (System.Uri baseUri, System.String
relativeUri) [0x00000] in :0 
  at System.Xml.XmlUrlResolver.ResolveUri (System.Uri baseUri, System.String
relativeUri) [0x00000] in :0 
  at Mono.Xml2.XmlTextReader.ReadStartTag () [0x00000] in :0 
  at Mono.Xml2.XmlTextReader.ReadContent () [0x00000] in :0 
  at Mono.Xml2.XmlTextReader.Read () [0x00000] in :0 
  at System.Xml.XmlTextReader.Read () [0x00000] in :0 
  at Mono.Xml.XmlFilterReader.Read () [0x00000] in :0 
  at Mono.Xml.XmlFilterReader.Read () [0x00000] in :0 
  at System.Xml.XmlReader.ReadEndElement () [0x00000] in :0 
  at System.Xml.Linq.XElement.LoadCore (System.Xml.XmlReader r, LoadOptions
options) [0x00000] in :0 
  at System.Xml.Linq.XNode.ReadFrom (System.Xml.XmlReader r, LoadOptions
options) [0x00000] in :0 
... 

2 个答案:

答案 0 :(得分:3)

以下是我停止XML解决方案的方法:

var r = new System.Xml.XmlTextReader(new StringReader(xml));
r.XmlResolver = new Resolver();

var doc = XDocument.Load(r);

class Resolver : System.Xml.XmlResolver {
    public override Uri ResolveUri (Uri baseUri, string relativeUri)
    {
        return baseUri;
    }
    public override object GetEntity (Uri absoluteUri, string role, Type type)
    {
        return null;
    }       
    public override ICredentials Credentials {
        set {
        }
    }
}

如果这是正确的,请告诉我。

答案 1 :(得分:2)

您只需清除XmlResolver

即可
r.XmlResolver = null;

创建XmlReader的推荐方法是使用通用XmlReader.Create(),在这种情况下:

XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = null;
XmlReader r = XmlReader.Create(new StringReader(xml), settings);      

使用.NET 4.0或更高版本,您还可以完全禁用DTD的处理(URI来自的位置):

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
XmlReader r = XmlReader.Create(new StringReader(xml), settings);