开发者

Trying to parse xml, but xmldocument.loadxml() is trying to download?

I have a string input that i do not know whether or not is valid xml.

I think the simplest aprroach is to wrap

new XmlDocument().LoadXml(strINPUT);

In a try/catch.

The problem im facing is, sometimes strINPUT is an html file, if the header of this file contains

<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xml:lang=""en-GB"" xmlns=""http://www.w3.org/1999/xhtml"" lang=""en-GB"">

...like many do, it actually tries to make a connection to the w3.org ur开发者_运维知识库l, which i really dont want it doing.

Anyone know if its possible to just parse the string without trying to be clever and checking external urls? Failing that is there an alternative to xmldocument?


Try the following:

XmlDocument doc = new XmlDocument();
using (var reader = XmlReader.Create(new StringReader(xml), new XmlReaderSettings() {
    ProhibitDtd = true,
    ValidationType = ValidationType.None
})) {
    doc.Load(reader);
}

The code creates a reader that turns off DTD processing and validation. Checking for wellformedness will still apply.

Alternatively you can use XDocument.Parse if you can switch to using XDocument instead of XmlDocument.


I am not sure about the reason behind the problem but Have you tried XDocument and XElement classes in System.Xml.Linq

 XDocument document = XDocument.Load(strINPUT , LoadOptions.None);
 XElement element = XElement.Load(strINPUT );

EDIT: for xml as string try following

XDocument document = XDocument.Parse(strINPUT , LoadOptions.None );


Use XmlDocument's load method to load the xml document, use XmlNodeList to get at the elements, then retrieve the data ... try the following:

XmlDocument xmlDoc = new XmlDocument();
//use the load method to load the XML document from the specified stream.
xmlDoc.Load("myXMLDoc.xml");
//Use the method GetElementsByTagName() to get elements that match the specified name.
XmlNodeList item = xDoc.GetElementsByTagName("item");
XmlNodeList url = xDoc.GetElementsByTagName("url"); 
Console.WriteLine("The item is: " + item[0].InnerText));

add a try/catch block around the above code and see what you catch, modify your code to address that situation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜