开发者

XDocument.Parse fails due to resolution error, how to disable resolution

I am trying to parse the contents of http://feeds.feedburner.com/riabiz using XDocument.Parse(string) (because it gets cached in a DB.)

However, it keeps failing with the below stack trace when it tries to resolve some URIs in that XML.

I don't care about validation or any of that XML nonsense, I just want the structure parsed. How can I use XDocument without this URI resolution?

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 
... 


Here's how I'm stopping the XML Resolution:

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 {
        }
    }
}

Please let me know if this is correct.


You can simply clear the XmlResolver:

r.XmlResolver = null;

The recommanded way to create XmlReader is using the generic XmlReader.Create(), in such case:

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

Using .NET 4.0 or later you can also completely disable the processing of DTDs (that is where the URIs came from):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜