【问题标题】:how to write a element in a xml file如何在xml文件中写入元素
【发布时间】:2014-03-20 14:17:58
【问题描述】:

我正在写一个xml文件,但是当我开始写元素时,它会出现一些错误,当我尝试通过代码读取xml文件时,它找不到这些元素。

<?xml version="1.0" encoding="utf-8" ?>
<options>
  <difficulty>
    <type name="Easy" health="6" active="0"/>
    <type name="Normal" health="4" active="1"/>
    <type name="Hard" health="2" active="0"/>
  </difficulty>
  <soundvolume>
    <type name="Sound" value="100"/>
    <type name="tempSound" value="100"/>
  </soundvolume>
</options>

这是目前为止的 xml 代码,但如果我不能让它工作,我不想继续。

这是我得到的错误:

找不到元素“选项”的架构信息。

并且每个元素都有相同的错误。 我使用 Visual Studio 2013 并有一个 Windows 窗体应用程序 C# 项目

这就是我读取 xml 文件的方式:

StreamReader sr = new StreamReader("Options.xml");
            String xmlsr = sr.ReadToEnd();
            sr.Close();

            XElement xDocumentSr = XElement.Parse(xmlsr);
            XElement xOptionsSr = xDocumentSr.Element("options");
            XElement xDifficultySr = xOptionsSr.Element("difficulty");

            foreach (XElement xType in xDifficultySr.Descendants("type"))
            {
                if(Convert.ToInt32(xType.Attribute("activate").Value) == 1)
                {
                    labDifficulty.Text = xType.Attribute("name").Value;
                }
            }

错误发生在她:

XElement xOptionsSr = xDocumentSr.Element("options");

我得到这个错误:

Splash Screen.exe 中出现“System.NullReferenceException”类型的未处理异常

附加信息:对象引用未设置为对象的实例。

当处于调试模式时,我可以看到元素为 = null

【问题讨论】:

  • 你能告诉我们你是怎么写/读的吗?
  • XML != 代码。请显示您的 C# 代码并在您的代码中显示错误发生的位置。

标签: c# xml visual-studio-2013 xelement


【解决方案1】:

这里:

XElement xDocumentSr = XElement.Parse(xmlsr);
XElement xOptionsSr = xDocumentSr.Element("options");

xDocumentSr 本身 options。所以你正在寻找 options 自身内部的元素。你不需要那个 xDocumentSr.Element("options");。你可以像这样简化你的代码:

var xmlDocument = XDocument.Load("Options.xml");

var element = xmlDocument.Root
              .Element("difficulty")
              .Elements("type")
              .FirstOrDefault(x => (int)x.Attribute("active") == 1);

if(element != null)
      labDifficulty.Text = element.Attribute("name").Value;

【讨论】:

  • 当我执行此 Selman22 时,我收到此错误:System.Xml.Linq.dll 中发生“System.ArgumentNullException”类型的未处理异常附加信息:值不能为空。
  • @user3407591 抱歉,这是我的小错误。在 firstOrDefault 中将 name 更改为 active
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-03
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 2011-03-04
相关资源
最近更新 更多