我在使用 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>
我想让每个联系人将其映射到对象联系人上。为此,我使用以下代码片段:
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);
好的,不要介意所有这些:专注于这一点:
当我得到根节点时,一切正常,我得到它正确。
当我使用 select 指令时,我试图让每个节点都说: from 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 (“名称”)而且它也不起作用!!!!!!!!!!这到底是什么????????????看来我的名字与我通过的名字不匹配,但这怎么可能。我知道 Elements() 函数采用重载的一个参数,该参数是一个映射到字符串的 XName。请考虑我编写的代码来自一个示例,它应该可以工作。