从 XmlDocument 到 XmlReader .Net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9025100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
From XmlDocument To XmlReader .Net
提问by user1107078
After an advice from a user that answered to my question I'm tring to convert my XmlDocument code to XmlReader code but I'm having some troubles.
在回答了我的问题的用户的建议之后,我试图将我的 XmlDocument 代码转换为 XmlReader 代码,但我遇到了一些麻烦。
This is XML (generated from php-mysql Page)
这是 XML(从 php-mysql 页面生成)
<row>
<idLink>64</idLink>
<idHost>3</idHost>
<url>http://www.google.com</url>
</row>
<row>
<idLink>68</idLink>
<idHost>4</idHost>
<url>http://www.bing.com</url>
</row>
..... until about 10000 rows
This is my XmlDocument code:
这是我的 XmlDocument 代码:
xmlDoc.Load("http://www.myUrl.com/list.php");
if (xmlDoc.DocumentElement != null){
foreach (XmlNode node in xmlDoc.DocumentElement)
{
if (node.Name == "row")
{
list.Add(new Links {
idLink = Convert.ToInt32(node.ChildNodes[0].InnerText),
idHost = Convert.ToInt32(node.ChildNodes[1].InnerText),
url = node.ChildNodes[2].InnerText });
}
}
return list;
Now I have some trouble to Convert in XmlReader, I tried many code but I can't handle it.
现在我在 XmlReader 中转换时遇到了一些麻烦,我尝试了很多代码,但我无法处理。
using (XmlReader reader = new XmlTextReader("http://myUrl.com/list.php"))
{
if (reader.NodeType == XmlNodeType.Element)
?????
采纳答案by dblood
If you are doing read only operations on an xml file then you can you use XmlReaderbut as @Marc Gravell points out it is difficult.
如果您对 xml 文件进行只读操作,那么您可以使用,XmlReader但正如@Marc Gravell 指出的那样,这很困难。
In this situation I will create a class that wraps an XPathDocumentusing an XmlReader. I then create an XPathNavigatorto read the data. Here's an example:
在这种情况下,我将创建一个XPathDocument使用XmlReader. 然后我创建一个XPathNavigator来读取数据。下面是一个例子:
public class MyXmlReader
{
public MyXmlReader(string xml)
{
StringReader sReader = new StringReader(xml);
XPathDocument xml = new XPathDocument(XmlReader.Create(sReader));
xmlNav = xml.CreateNavigator();
}
private XPathNavigator xmlNav = null;
public MyDataModel ReadMyDataModel()
{
MyDataModel model = new MyDataModel();
model.Read(xmlNav);
return model;
}
}
As shown above, the reading of the data can then be encapsulated into an associated object model. You can see some details in my answer on this question:
如上所示,然后可以将数据的读取封装到关联的对象模型中。你可以在我对这个问题的回答中看到一些细节:
How do I manipulate an XML document one parent element at a time?
回答by Wernight
You can use
您可以使用
XmlReader xmlReader = new XmlNodeReader(xmlDoc);
See: http://blog.jongallant.com/2007/01/convert-xmldocument-to-xmlreader.html
参见:http: //blog.jongallant.com/2007/01/convert-xmldocument-to-xmlreader.html

