문제

I've been working on a project (C#) and part of it was filling a data grid with an embedded xml file.

Although I've now found a way to make this work, i am still confused as to to theory behind it. And I'd like to stop and make sure i fully understand it before i continue with this project.

The code that i have working currently is;

XmlDataDocument myXML = new XmlDataDocument();  
StringReader mytempXML = (new StringReader(BasicTest.Properties.Resources.myxml));
myXML.DataSet.ReadXml(mytempXML);

What is confusing to me is that before this solution, I was trying the below;

myXML.DataSet.ReadXml(BasicTest.Properties.Resources.myxml);

and it wasn't working. However using the full file path (like below) was working.

myXML.DataSet.ReadXml("C:/..etc../myxml.xml");

The Question I have is: why is a StringReader required for the ReadXml method if you're reading from a resource, but using a full file path works without?

If anyone could provide an explanation, that would be great. Thanks.

도움이 되었습니까?

해결책

This is because the ReadXml method takes a string. That string must be the name of a file. It cannot be XML. If you pass it a string that is XML, it will think that is the name of the file! It doesn't have the smarts to look at the string and ask "Is this string XML, or is it a file name?" and figure that out.

// Summary:
//     Reads XML schema and data into the System.Data.DataSet using the specified
//     file.
//
// Parameters:
//   fileName:
//     The filename (including the path) from which to read.
public XmlReadMode ReadXml(string fileName);

By wrapping the XML in a stringreader or a stream or something, you are calling a different overload, that expects XML instead of a file name.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top