【问题标题】:How Read Xml File from Project Directory in C#?如何从 C# 中的项目目录中读取 Xml 文件?
【发布时间】:2015-07-01 22:29:21
【问题描述】:

我需要知道如何从项目目录中读取 xml 文件,如下代码所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using crudpartialviewsjqureyajax.Models;
using System.Data;
using System.Xml;

namespace crudpartialviewsjqureyajax.Controllers
{

    public class snehprajapatController : Controller
    {

        public void getinstructors()
        {
            try
            {
                List<string> name = null;
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(@"~\App_Data\Trainings.xml");//Here given xml path location
                XmlNodeList xnList = xml.SelectNodes("/Trainings/Training");
                foreach (XmlNode xn in xnList)
                {
                    new List<string>{
                xn["name"].InnerText
                };

                }

                //return name;
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }

        }
    }
}

这里出现错误是:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll

Additional information: Data at the root level is invalid. Line 1, position 1.

请查看上面的代码并建议我为此做什么?

提前致谢。

【问题讨论】:

标签: c#


【解决方案1】:

LoadXml 用于加载文字 XML 字符串,而不是用于指向文件路径。毫不奇怪,您的路径不是有效的 XML。您可以使用xml.Load("...") 从文件中加载到XmlDocument

但是,我强烈建议您改用 LINQ to XML,除非您有充分的理由使用旧的 XmlDocument API。我已根据您的代码进行了猜测,但如果您的 XML 不是以这种方式构建,这可能无法正常工作。

var doc = XDocument.Load(@"~\App_Data\Trainings.xml");

var instructorNames = doc.Descendants("Training")
    .Elements("name")
    .Select(e => e.Value)
    .ToList();

【讨论】:

    【解决方案2】:

    您应该用 xml.Load 方法替换 xml.LoadXml,因为: XmlDocument.Load :用于从流、TextReader、路径/URL 或 XmlReader 加载 XML。 而XmlDocument.LoadXml 用于加载包含在字符串中的 XML。

    所以你的代码应该是这样的:

    xml.Load(@"~\App_Data\Trainings.xml");//Here given xml path location
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多