我是一个有用的助手,可以为您翻译文本。
我有一个使用Linq To Xml的问题。
这是一个简单的代码。我有这个XML:
<?xml version="1.0" encoding="utf-8" ?>
<data xmlns="http://www.example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/directory file.xsd">
<contact>
<name>aaa</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>sss</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>bbb</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
<contact>
<name>ccc</name>
<email>email@email.ext</email>
<birthdate>2002-09-22</birthdate>
<telephone>000:000000</telephone>
<description>Description for this contact</description>
</contact>
我希望将每个联系人映射到一个名为Contact的对象上。为此,我使用以下代码片段:
我想要获取每个联系人并将其映射到一个名为Contact的对象上。为了实现这一目标,我使用了以下代码片段:
XDocument XDoc = XDocument.Load(System.Web.HttpRuntime.AppDomainAppPath + this.filesource);
XElement XRoot = XDoc.Root;
//XElement XEl = XElement.Load(this.filesource);
var results = from e in XRoot.Elements("contact")
select new Contact((string)e.Element("name"), (string)e.Element("email"), "1-1-1", null, null);
List<Contact> cntcts = new List<Contact>();
foreach (Contact cntct in results) {
cntcts.Add(cntct);
}
Contact[] c = cntcts.ToArray();
// Encapsulating element
Elements<Contact> final = new Elements<Contact>(c);
好的,不要关注前面的内容,重点在这里:
当我获取根节点时,一切都没问题,我成功地获取了它。
当我使用选择指令尝试获取每个节点时,我会写成:从 e in
XRoot.Elements("contact")
好的,这里是问题:如果我使用:from e in XRoot.Elements(),我会得到所有联系人节点,但如果我使用:from e in XRoot.Elements("contact"),我什么也得不到:空集。
好吧,你告诉我:使用另一个:好的,那么我们使用:from e in XRoot.Elements()
,我无论如何都能得到所有节点,没错,但是接下来就出现了另一个问题:
当说: select new Contact((string)e.Element("name"), (string)e.Element("email"), "1-1-1", null, null);
我试图访问<name>, <email>
... 我必须使用.Element("name"),但它也不起作用!!!这是怎么回事?似乎它不匹配我传递的名称。但这怎么可能呢?我知道Elements()函数可以重载,接受一个XName参数,该参数映射到一个字符串。请注意,我所写的代码来自一个例子,它应该工作。