0

我正在尝试读取一些 xml 文件,这些文件包含在我的项目下的 Resources 文件夹中。下面是我的代码:

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.
}

但是当我编译时,“QP2020E.Properties.Resources.ID01”出现错误:“路径中有非法字符。” 你们知道怎么回事吗?

4

3 回答 3

1

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)); 
于 2012-09-26T06:53:59.227 回答
1

您应该提供XMLTextReader文件路径而不是文件内容。例如,改变

reader = new XmlTextReader(MyProject.Properties.Resources.ID01);

至:

StringReader s = new StringReader(MyProject.Properties.Resources.XmlFile);
XmlTextReader r = new XmlTextReader(s);
于 2012-09-26T07:22:13.407 回答
0

要从资源中读取 XML 文件,请使用此答案中描述的 XDocument.Parse

我认为你需要修改你的代码是这样的:

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
}

关于XDocument的更多信息在这里。

于 2012-09-26T06:59:51.207 回答