用于存储信息的简单 XML 文件

本文关键字:XML 文件 简单 存储 信息 用于 | 更新日期: 2023-09-27 18:32:11

我想创建一个简单的XML文件来存储一些可以在文本编辑器中轻松更改的设置。这是我的XML文件:

<connection>
  <hostname>the.host.name</hostname>
  <port>1000</port>
  <database>theDbName</database>
</connection>

我现在正在尝试使用 Linq to XML 将该信息读入我的程序,但它给了我一个错误:

找不到源类型"System.Xml.Linq.XElement"的查询模式的实现。 未找到"选择"。

我的代码如下:

XElement root = XElement.Load(".''Resources''Connection.xml");
string host = from el in root.Element("hostname") select el.Element("text");

用于存储信息的简单 XML 文件

XDocument xDoc = XDocument.Load(".''Resources''Connection.xml");
string host = (string)xDoc.Root.Element("hostname");

我想你对你的XML结构应该是什么样子以及你用LinQ读取XML的方式感到困惑。首先,将您的连接元素放在名为 connections 的根中。您的 XML 现在如下所示:

<?xml version="1.0" encoding="utf-8"?>
<connections>
    <connection>
        <hostname>the.host.name</hostname>
        <port>1000</port>
        <database>theDbName</database>
    </connection>
</connections>

现在,您可以选择该根下的元素并从中读取所有数据。示例代码如下所示:

var root = XElement.Load(".''Resources''Connection.xml");
var connection = root.Elements("connection").FirstOrDefault();
if(connection != null)
{
    var host = connection.Element("hostname").Value;
    //do something with 'host'
}

更新:

如果您不想要根元素"连接",则可以省略它并使用以下代码读取 XML:

var xmlDoc = XDocument.Load("G:''Connection.xml");
var connection = xmlDoc.Descendants("connection").FirstOrDefault();
if(connection != null)
{
    var host = connection.Element("hostname").Value;
    //do something with 'host'
}