如何更正代码以读取 xml 文件?
该代码按原样工作,但是当我在 doc.Loadxml 中引用外部 xml 文件时,它停止工作。我怎样才能让它发挥作用?我不太明白。
我用它来调用 GetXmlData 并为 gridview 提供源:GridView1.ItemsSource = GetXmlData();
private static object GetXmlData()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Products>
<Product>
<ID>1</ID>
<Name>ASP.NET</Name>
</Product>
</Products>
");
XmlDataProvider provider = new XmlDataProvider();
provider.IsAsynchronous = false;
provider.Document = doc;
provider.XPath = "Products/Product";
return new ObservableCollection<XmlNode>((IEnumerable<XmlNode>)provider.Data);
}
This code works as it is but when I reference an external xml file in doc.Loadxml, it stops working. How can I get it to work? I don't quite understand.
I use this to call GetXmlData and provide source for the gridview :GridView1.ItemsSource = GetXmlData();
private static object GetXmlData()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Products>
<Product>
<ID>1</ID>
<Name>ASP.NET</Name>
</Product>
</Products>
");
XmlDataProvider provider = new XmlDataProvider();
provider.IsAsynchronous = false;
provider.Document = doc;
provider.XPath = "Products/Product";
return new ObservableCollection<XmlNode>((IEnumerable<XmlNode>)provider.Data);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你需要
而不是
You need
instead of
XMLDocument
有多个Load
方法,请参阅它们及其描述:您正在使用最后一个,其描述用于从字符串加载 XML。
由于您需要从文件加载 XML,因此您必须使用
Load
方法,而不是LoadXml
。我认为第二种方法更适合你的情况。您可以传递 XML 文件的完整路径。XMLDocument
has severalLoad
methods, see them with their description:You're using the last one which is as described used to load XML from a string.
Since you need to load the XML from a file, so you've to use to
Load
method, as opposed toLoadXml
. I think second method is better suited for your situation. You can pass the fullpath of the XML file.这应该对您有帮助:
您调用的方法仅从字符串加载 xml。您需要从需要不同方法的文件中读取它。
This should help you:
The method you are calling only loads xml from a string. You need to read it from a file which requires a different method.