如何在XML文件中编写元素

本文关键字:元素 文件 XML | 更新日期: 2023-09-27 17:51:03

我正在写一个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代码,但如果我不能让它工作,我不想继续。

这是我得到的错误:

找不到元素'options'的架构信息。

和每个元素都有相同的错误。我使用visual studio 2013,并有一个Windows Forms Application 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;
                }
            }

错误发生在her:

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

,我得到这个错误:

类型为"System"的未处理异常。NullReferenceException'在启动屏幕.exe中发生

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

,当在调试模式下,我可以看到元素是= null

如何在XML文件中编写元素

此处:

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;