I'm trying to read some xml files which I have included in the Resources folder under my project. Below is my code:
public void ReadXMLFile(int TFType)
{
XmlTextReader reader = null;
if (TFType == 1)
reader = new XmlTextReader(MyProject.Properties.Resources.ID01);
else if (TFType == 2)
reader = new XmlTextReader(MyProject.Properties.Resources.ID02);
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Number":
// more coding on the cases.
}
But when I compile, there's an error on "QP2020E.Properties.Resources.ID01" saying: 'Illegal characters in path.' Do you guys know what's wrong?
The XmlTextReader constructor requires either a stream or a string. The one that requires a string is expecting a url (or path). You are passing it the value of your resource. You'll need to convert the string value into a stream.
To do this Wrap it in a StringReader(...)
reader = new XmlTextReader(new StringReader(MyProject.Properties.Resources.ID02));
You should provide the XMLTextReader
with the file path not the file content. For instance, change
reader = new XmlTextReader(MyProject.Properties.Resources.ID01);
To:
StringReader s = new StringReader(MyProject.Properties.Resources.XmlFile);
XmlTextReader r = new XmlTextReader(s);
To read an XML file from a resource, use XDocument.Parse as described in this answer
I think you need to modify your code to be like this:
public void ReadXMLFile(int TFType)
{
XDocument doc = null;
if (TFType == 1)
doc = XDocument.Parse(MyProject.Properties.Resources.ID01);
else if (TFType == 2)
doc = XDocument.Parse(MyProject.Properties.Resources.ID02);
// Now use 'doc' as an XDocument object
}
More info on XDocument is here.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.