正在读取C#中的.XML文件

本文关键字:XML 文件 中的 读取 | 更新日期: 2023-09-27 18:20:33

在过去的几个小时里,我一直在尝试从.xml文件中读取,但几乎没有成功。

我试过了:

XmlReader reader = XmlReader.Create("ChampionList.xml");
        reader.ReadToFollowing("Name");
        reader.MoveToFirstAttribute();
        string nume = reader.Value;
        MessageBox.Show(nume);

我的xml如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<main>
  <Champion>
    <Name>Aatrox</Name>
    <Counter>Soraka</Counter>
  </Champion>
  <Champion>    
    <Name>Ahri</Name>
    <Counter>Diana</Counter>    
  </Champion>
</main>

每当我按下按钮时,我都想读一下名字和计数器。每次都有一个新的(按下第一个按钮-第一个冠军,依此类推)。

有人能帮我吗?此外,对代码做一点解释也很好,如果有很多循环之类的东西,我还有很多东西要学。

正在读取C#中的.XML文件

您可能会发现使用比XmlReader更高级的接口更容易。例如,您可以在Linq-to-XML中执行以下操作:

// read in the entire document
var document = XDocument.Load("ChampionsList.xml");
// parse out the relevant information
// start with all "Champion" nodes
var champs = documents.Descendants("Champion")
    // for each one, select name as the value of the child element Name node
    // and counter as the value of the child element Counter node
    .Select(e => new { name = e.Element("Name").Value, counter = e.Element("Counter").Value });
// now champs is a list of C# objects with properties name and value
foreach (var champ in champs) {
    // do something with champ (e. g. MessageBox.Show)
}

为了测试XML的有效性,我发现将文件的扩展名设置为.XML,然后将其放到Internet Explorer窗口中非常容易。InternetExplorer内置了一个非常好的XML查看器,它会让你知道是否有错误。

(EDIT:删除了关于呈现的XML无效的特定建议——这似乎是由标记问题引起的。)

使用ReadElementContentAsString获取元素的内容

XmlReader reader = XmlReader.Create("ChampionList.xml");
reader.ReadToFollowing("Name"); // read until element named Name
string nume = reader.ReadElementContentAsString(); // read its content
MessageBox.Show(nume);

为什么不把它们读到列表中一次,当按下按钮时,只需从列表中取出。XmlTextReader阅读器=新的XmlTextReader("yourfile.xml");

            string elementName = "";
            List<string[]> Champion = new List<string[]>();
            string name = "";            
            while (reader.Read())  // go throw the xml file
            {
                if (reader.NodeType == XmlNodeType.Element) //get element from xml file 
                {
                    elementName = reader.Name;
                }
                else
                {
                    if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) //fet the value of element
                    {
                        switch (elementName) // switch on element name weather Name or Counter
                        {
                            case "Name":
                                name = reader.Value;
                                break;
                            case "Counter":
                                string[] value = new string[] { name, reader.Value }; //store result to list of array of string
                                Champion.Add(value);
                                break;
                        }
                    }
                }
            }